Backbone - 可以从模型中获取集合

时间:2013-04-12 04:01:06

标签: javascript backbone.js

我想知道是否有办法从其中一个模型中获取对集合的引用。例如,如果下面集合中的任何人以某种方式知道属于集合或多个集合。 Fiddle

(function() {
window.App = {
    Models: {},
    Views: {},
    Collections: {}
};

App.Models.Person = Backbone.Model.extend({
    defaults: {
        name: 'John',
        phone: '555-555-5555'
    }
});

App.Views.Person = Backbone.View.extend({
    tagName: 'li',

    template: _.template("<%= name %> -- <%= phone %>"),

    render: function(){
        var template = this.template( this.model.toJSON() );

        this.$el.html( template );

        return this;
    }
});

App.Collections.People = Backbone.Collection.extend({
    model: App.Models.Person 
});

App.Views.People = Backbone.View.extend({
    tagName: 'ul',

    add: function(person){
        var personView = new App.Views.Person({ model: person });

        this.$el.append( personView.render().el );

        return this;
    },

    render: function() {
        this.collection.each(this.add, this);

        return this;
    }
});


})();

var peeps = [ { name: 'Mary' }, { name: 'David' }, { name: 'Tiffany' } ];

var people = new App.Collections.People(peeps);

var peopleView = new App.Views.People({ collection: people });

peopleView.render().$el.appendTo('body');

1 个答案:

答案 0 :(得分:25)

每个模型都有一个名为collection的属性。在你的小提琴中,添加console.log(people.models[0].collection)将打印出该集合。

查看源代码,看起来这就是用来执行调用模型的destroy()方法时从集合中删除模型的操作。

更新:请参阅this updated fiddle,其中会创建三个人模型和两个集合。它将它们打印到控制台。看起来model.collection仅指向该人被添加到的第一个集合,而不是第二个集合。

相关问题