0

我正在使用该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"});

这将返回具有火枪手工作的 2 个模型。

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

4

1 回答 1

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/

于 2012-11-27T03:22:03.330 回答