Backbone:在不同的集合中显示返回的模型

时间:2012-11-27 03:03:00

标签: javascript backbone.js

我正在使用where方法从集合中获取某些特定模型。类似于骨干网站的例子:

var friends = new Backbone.Collection([
  {name: "Athos",      job: "Musketeer"},
  {name: "Porthos",    job: "Musketeer"},
  {name: "Aramis",     job: "Guard"},
  {name: "d'Artagnan", job: "Guard"},
]);

var musketeers = friends.where({job: "Musketeer"});

这将返回具有Musketeer作业的2个模型。

如何将这两个Musketeer模型放入一个新的集合并为它渲染一个collectionView?

1 个答案:

答案 0 :(得分:0)

您可以使用collection.reset将其传递给新收藏集。然后只需将其传递给视图并进行渲染。

var MyView = Backbone.View.extend({
    el: "#container",

    template: _.template($("#templ").html()),

    render: function() {
        var self = this;
        _.each(this.collection.models, function(model) {
            self.$el.append(self.template(model.toJSON()));
        });
    }        
});

var friends = new Backbone.Collection([
  {name: "Athos",      job: "Musketeer"},
  {name: "Porthos",    job: "Musketeer"},
  {name: "Aramis",     job: "Guard"},
  {name: "d'Artagnan", job: "Guard"},
]);

var musketeers = friends.where({job: "Musketeer"});

var newCollection = new Backbone.Collection();
newCollection.reset(musketeers);

var view = new MyView({ collection: newCollection });
view.render();

http://jsfiddle.net/k3JEz/1/