我使用 Backbone 集合的重置方法在页面加载时将一堆 JSON 数据直接引导到集合中。
文档提供了一些线索,表明可能是这种情况,但是当我这样做时,集合或模型的解析方法都不会被触发。这真的很烦人。
这里是一些示例代码:
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'));
请参阅下面的 fiddle : http://jsfiddle.net/JonRed/zW68M/2/
我希望这两个“调试器”语句都能在这里被命中,但正如您所看到的,两者都没有。 文档指出“parse”仅在集合的 fetch 方法上触发,但这将涉及我根本不需要的第二个 ajax 调用。
任何人都可以建议我使用一种技术来获取集合的重置方法来触发解析方法吗?
谢谢
最佳答案
Collection#reset
采用第二个 options
参数。文档没有提到它,但您可以在 options
中传递 parse: true
来获取 reset
来调用 parse
>:
categories.reset([...], { parse: true });
最小演示:http://jsfiddle.net/ambiguous/2BJdq/
更新您的 fiddle 版本:http://jsfiddle.net/ambiguous/whb7m/
reset
最终调用 Collection#set
完成大部分繁重的工作,并在调用 set
时传递 options
。 set
也不记录 parse: true
行为,但您can see it in the code :
set: function(models, options) {
//...
if (options.parse) models = this.parse(models, options);
说实话,我根据 API 的其他部分猜测选项中的 parse: true
可能会起作用并尝试过,然后我通过跟踪来寻找合理性文档和源代码。
关于javascript - 使用 collection.reset 不会触发集合的解析方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22432376/