简体   繁体   English

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

[英]Backbone - Possible to get the collection from a model

I'm wondering if there's a way to get a reference to a collection from one of its models. 我想知道是否有办法从其中一个模型中获取对集合的引用。 For instance, if any of the people in the collection below are somehow aware of belonging to a collection, or multiple collections. 例如,如果下面集合中的任何人以某种方式知道属于集合或多个集合。 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');

Each model has a property called collection . 每个模型都有一个名为collection的属性。 In your fiddle, adding console.log(people.models[0].collection) will print out the collection. 在你的小提琴中,添加console.log(people.models[0].collection)将打印出该集合。

Looking through the source code, it looks like this is what's used to do things like remove a model from a collection when the model's destroy() method is called. 通过源代码查看,看起来这就是用于执行诸如调用模型的destroy()方法时从集合中移除模型的操作。

Update: see this updated fiddle which creates three person models and two collections. 更新:看到这个更新的小提琴 ,创建三个人模型和两个集合。 It prints them to the console. 它将它们打印到控制台。 It looks like model.collection only refers to the first collection the person was added to, not the second. 看起来model.collection只是指第一个人被添加到的集合,而不是第二个集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM