簡體   English   中英

Backbone重置fetch上的集合

[英]Backbone reset a collection on fetch

這是我的問題:

  • 我有一個包含集合的容器視圖。
  • 在頁面加載時,我得到一些模型,用它們填充這個集合,然后渲染模型
  • 我開火和事件
  • 當這個事件觸發時,我想調用我的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)
    }
});

但是當我得到它們時,我不知道如何處理這些模型。

任何推向正確的方向將不勝感激!

精細手冊

fetch collection.fetch([options])

[...]當模型數據從服務器返回時,它使用set來(智能地)合並獲取的模型,除非你傳遞{reset: true} ,在這種情況下,集合將被(有效地) 重置

因此,您只需要在選項中包含reset: true ,並且fetch將調用reset以使用獲取的模型替換集合的內容:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM