将模型添加到Backbone中的Collection

时间:2012-07-26 18:58:57

标签: collections backbone.js model

  

可能重复:
  Backbone.js Empty Array Attribute

我一直在研究一个骨干项目并遇到了问题,所以我简单地嘲笑它,但后来遇到了一些我不理解的事情。这是代码:

(function(){
    myModel = Backbone.RelationalModel.extend({
        idAttribute: 'id',
        relations: [{
            type: Backbone.HasMany,
            key: 'mysubmodels',
            relatedModel: 'mySubmodel',
            reverseRelation: {
                key: 'mymodel',
                includeInJSON: 'id',
            },
        }],
    });
    mySubmodel = Backbone.RelationalModel.extend({
        idAttribute: 'id',
    });
    myCollection = Backbone.Collection.extend({
        model: myModel,
    }); 
    myView = Backbone.View.extend({
        initialize: function(){
            this.collection.bind('add', this.doSomething);
        },
        doSomething: function(){
            console.log('a model has been added')
        },
    });
}());

$(document).ready(function(){   
    var data = {
        id:1,
        data: 'this is one',
        mysubmodel: {
            data: 'hello'
        }           
    };

    var cltn = new myCollection();
    console.log(cltn);
    var vw = new myView({collection: cltn});

    var mdl = new myModel(data);
    cltn.add(mdl);
    console.log(cltn);
});

基本上,让我困惑的部分是底部的两个'console.log(cltn)'都注册了一个模型已被添加,尽管模型是在之后添加的 >第一个日志。

0 个答案:

没有答案