簡體   English   中英

使用collection.reset不會觸發集合的parse方法

[英]Using collection.reset doesn't fire the collection's parse method

我正在使用Backbone集合的reset方法在頁面加載時將大量JSON數據直接引導到集合中。

該文檔提供了一些線索,可能是這種情況,但是當我這樣做時,都不觸發Collection或Models的parse方法。 真煩人。

這是一些示例代碼:

var ablefutures = {};

ablefutures.category = Backbone.Model.extend({
    idAttribute : 'categoryId',

    parse : function(response)
    {
        debugger;
        response.categoryDetailItems = new ablefutures.categoryDetailItems(response.categoryDetailItems);

        return response;
    }
});


ablefutures.categories = Backbone.Collection.extend({

    model: ablefutures.category,
    url: '../api/categoriesRouter.php',
    parse : function(response)
    {
        debugger;

        return response
    }
});

categories = new ablefutures.categories();

categories.reset([{"categoryId":1,"name":"Eyewear","heroText":"<div>The complete <span class=\"stand-out\">eyewear<\/span> solution<\/div><div class=\"subText\">Eye protection for clinicians and patients.<\/div>","categoryDetailItems":[{"categoryDetailId":1,"description":"gdfsgdfgdfgdfgdf"}],"created":null,"lastUpdated":null,"status":1}]);

category = categories.get(1);

$('#category').html(category.get('categoryId'));

參見下面的小提琴: http : //jsfiddle.net/JonRed/zW68M/2/

我希望這兩個“ debugger”語句都會在這里被擊中,但是正如您所看到的,兩者都不會。 文檔指出,“ parse”僅在集合的fetch方法上觸發,但這將涉及第二個ajax調用,而我根本不需要。

誰能建議我可以用來獲取集合的reset方法來觸發解析方法的技術?

謝謝,

Collection#reset使用第二個options參數。 該文檔沒有提及它,但是您可以在options傳遞parse: true ,以reset為調用parse

categories.reset([...], { parse: true });

最小演示: http : //jsfiddle.net/ambiguous/2BJdq/
小提琴的更新版本: http : //jsfiddle.net/ambiguous/whb7m/

reset最終調用Collection#set來完成大部分繁重的工作,並且在調用set時會傳遞options set沒有記錄parse: true行為,但您可以在代碼中看到它

set: function(models, options) {
  //...
  if (options.parse) models = this.parse(models, options);

老實說,我猜測是基於該API的其他部分進行的parse: true選項中的parse: true可能起作用並嘗試了它,然后我通過跟蹤文檔和源代碼來找到理由。

暫無
暫無

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

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