Backbone重置fetch上的集合

时间:2013-09-21 05:16:17

标签: 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);
    };
};

我感兴趣的是:

    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)
    }
});

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

任何推向正确方向的人都会受到赞赏!

1 个答案:

答案 0 :(得分:8)

来自fine manual

  

抓取 collection.fetch([options])

     

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

因此,您只需在选项中加入reset: truefetch将调用reset以使用获取的模型替换集合的内容:

this.collection.fetch({
    data: { ... },
    reset: true
});