嵌套模型在骨干中充满了数据

时间:2013-02-22 10:39:52

标签: backbone.js backbone-views backbone-events backbone-relational backbone-model

我创建了一个模型(RuleModel),它的属性是其他模型(RuleInformationModel)。但是在传递json(SampleRule)数据时,内部模型没有被填充。

当我做控制台时,iam变得不确定。所以我在cosole中检查了RuleInformationModel,它只有样本json的默认值值没有被添加到这个内部模型中。

var  SampleRule = {
    RuleId: 1,
    Information: [{ 
        RuleId:1,
        RuleName: 'Diwali Offer', 
        MerhantId: '565cfa73-8f12-4876-b2cf-2e61a28eddca', 
        StartDate: '1/1/0001 12:00:00 AM', 
        EndDate: '1/1/0001 12:00:00 AM', 
        IsActive: 'True', 
        Description: 'Diwali Offer for Samsung products',
        RuleSetId: 1 ,
        Status:'False'
}],
    Conditions: {},
    Actions: {}
};

var RuleInformationModel = Backbone.Model.extend({

    defaults: {
        RuleId: '',
        RuleName: '', 
        MerchantId: '', 
        StartDate: '', 
        EndDate: '', 
        IsActive: '', 
        Description: '',
        RuleSetId: '',
        Status: 'False' 
    },
    idAttribute: "RuleId"
});

var RuleModel = Backbone.Model.extend({

    initialize: function (options) {
        this.RuleId = options.RuleId;
    },
    defaults: {
        RuleId: '',
        Information: new RuleInformationModel(),
        Conditions: {},
        Actions: {}
    },
    idAttribute: "RuleId",
    urlRoot: function () {
        return "../BackBoneApi/RuleEngine/" + this.RuleId
    },
    parse: function (response) {
        response = SampleRule;
        return response;
    }
});

var NewOrEditRuleView = Backbone.View.extend({

    tagName: 'div',
    template: ItemTemplate,
    initialize: function (options) {
        var self = this;
        self.model = new RuleModel({RuleId:options.RuleId});
        this.model.fetch();
        console.log(self.model.get('Information').get('RuleName'));
    },
    render: function (Purpose) {
        var self = this;
        var tmpl = _.template(self.template);
        console.log(self.model);
        self.$el.html(tmpl({ Purpose: Purpose, RuleName: self.model.get('Information').get('RuleName') }));
    }
});

1 个答案:

答案 0 :(得分:0)

不,它不会。你没有在实例化或解析SampleRule对象的地方发布代码,但我想我得到了你所说的。我建议你在RuleModel中创建一个方法来执行以下操作:

var RuleModel = Backbone.Model.extend({
   // As you were..
   // ...
    updateInformationModel: function(object) {
        // SampleRule.Information is an array, I assume this is by design? If so:
        this.get("Information").set(object.Information[0]);
    }
   // ...
});