这是我的问题:
这就是我设置模型/集合/视图的方式
var someModel = Backbone.Model.extend({});
var someCollection = Backbone.Collection.extend({
model: someModel,
url: "api/someapi"
});
var someView = Backbone.View.extend({
events: {
"click #refresh": "refreshCollection"
},
initialize: function () {
this.collection.bind("reset", this.render, this);
},
render: function () {
// render stuff
},
refreshCollection: function (e) {
this.collection.fetch({data: {someParam: someValue});
this.render();
}
});
var app = function (models) {
this.start = function () {
this.models = new someCollection();
this.view = new someView({collection: this.models});
this.view.reset(models);
};
};
我感兴趣的是:
refreshCollection: function (e) {
this.collection.fetch({data: {someParam: someValue});
this.render();
}
我传入一些参数,我的api返回一个json数组模型。我想摆脱集合中的所有现有模型,并将所有返回的模型放入集合中,然后更新视图(使用render())
我理解这可以通过collection.set或collection.reset实现。这两个都采用了一系列模型。我没有一系列模型可以传递。
我试过了:
this.collection.fetch({
data: {someParam: someValue},
success: function (response) {
doSomethingWith(response.models)
}
});
但是当我拿到它们时,我不知道如何处理这些模型。
任何推向正确方向的人都会受到赞赏!
答案 0 :(得分:8)
来自fine manual:
抓取
collection.fetch([options])
[...]当模型数据从服务器返回时,它使用 set 来(智能地)合并获取的模型,除非你通过
{reset: true}
,在这种情况下集合将(有效地)重置。
因此,您只需在选项中加入reset: true
,fetch
将调用reset
以使用获取的模型替换集合的内容:
this.collection.fetch({
data: { ... },
reset: true
});