Backbone重置fetch上的集合

Jim*_*tts 2 javascript backbone.js backbone-events

这是我的问题:

  • 我有一个包含集合的容器视图.
  • 在页面加载时,我得到一些模型,用它们填充这个集合,然后渲染模型
  • 我开火和事件
  • 当这个事件触发时,我想调用我的api(根据输入参数返回模型)
  • 然后,我想从集合中删除所有现有模型,使用我的新模型重新填充,然后渲染模型

这就是我设置模型/集合/视图的方式

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);
    };
};
Run Code Online (Sandbox Code Playgroud)

我感兴趣的是:

    refreshCollection: function (e) {
        this.collection.fetch({data: {someParam: someValue});
        this.render();
    }
Run Code Online (Sandbox Code Playgroud)

我传入一些参数,我的api返回一个json数组模型.我想摆脱集合中的所有现有模型,并将我所有返回的模型放入集合中,然后更新视图(使用render())

我理解这可以通过collection.set或collection.reset实现.这两个都采用了一系列模型.我没有传递的模型数组.

我试过了:

this.collection.fetch({
    data: {someParam: someValue},
    success: function (response) {
        doSomethingWith(response.models)
    }
});
Run Code Online (Sandbox Code Playgroud)

但是当我得到它们时,我不知道如何处理这些模型.

任何推向正确的方向将不胜感激!

mu *_*ort 8

精细手册:

collection.fetch([options])

[...]当模型数据从服务器返回时,它使用set来(智能地)合并获取的模型,除非你通过{reset: true},在这种情况下集合将被(有效地)重置.

所以你只需要包含reset: true在选项中,fetch然后调用reset用获取的模型替换集合的内容:

this.collection.fetch({
    data: { ... },
    reset: true
});
Run Code Online (Sandbox Code Playgroud)