javascript - 使用 collection.reset 不会触发集合的解析方法

标签 javascript json backbone.js

我使用 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 时传递 optionsset 也不记录 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/

相关文章:

c# - 在 javascript 中引用 ASP.NET Web 控件

javascript - AngularJS 使用 $broadcast 帮助在 Controller 之间共享数据

java - 当没有标记所有内容时,如何使用 Gson 解析 Json 数据

javascript - 实例化覆盖以前的实例(Backbone.js 模型)

javascript - Backbone.js View 是否需要 jQuery 或 Zepto? (或 : why am I getting “Uncaught TypeError: undefined is not a function” ? )

javascript - 如何在插件中访问嵌入式 cordova webview?

javascript - Simple&Basic JS - 第一次尝试 javascript(想要免费的 jQuery)

json - package.JSON 文件不完整?

javascript - JSON.stringify 中未捕获的 InvalidStateError

Javascript MVC,需要结构/方法方面的帮助吗?