![](/img/trans.png)
[英]Backbone - Why doesn't a collection.reset trigger a model event?
[英]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.