backbone.js - 重写的parse()不设置模型属性

Mik*_*sky 2 backbone.js

我有一个链接到两个子模型的模型,如下所示:

var SubModel = Backbone.Model.extend({
    defaults: {
        headline: null,
        image_url: null,
        url: null
    }
});

var MainModel = Backbone.Model.extend({
    defaults: {
        subModelA: null,
        subModelB: null,
        title: null
    },

    urlRoot: function() {
        if (this.isNew()) {
            return '/mainmodel/new';
        }
        return '/mainmodel';
    },

    initialize: function() {
        this.fetch();
    },

    parse: function(data) {
        var response = {};
        response.subModelA = new SubModel(data.subModelA);
        response.subModelB = new SubModel(data.subModelB);
        response.title = data.title;
        return response;
    }
});
Run Code Online (Sandbox Code Playgroud)

我目前遇到的问题是调用var mainModelInstance = new MainModel()是否正确获取,/mainmodel/newmainModelInstance.attributes始终是一个空白对象{}.

var mainModelInstance = new MainModel();
mainModelInstance.attributes; // Returns {}
Run Code Online (Sandbox Code Playgroud)

以下是服务器响应的示例/mainmodel/new:

{
    "title": "Politics",
    "subModelA": {
        "headline": "Investigators: Iran tried to smuggle suicide belts, missiles by boat into Yemen",
        "url": "http://dailycaller.com/2013/02/09/yemen-minister-says-weapons-came-from-iran/",
        "image_url": "http://cdn01.dailycaller.com/wp-content/uploads/2013/02/54c7d52e1a384db489ab9ea568afddb0-e1360455589316.jpg"
    },
    "subModelB": {
        "headline": "Review: Who needs Windows RT? Acer's Iconia W510 runs the real thing",
        "url": "http://arstechnica.com/gadgets/2013/02/review-who-needs-windows-rt-acers-iconia-w510-runs-the-real-thing/",
        "image_url": "http://cdn.arstechnica.net/wp-content/uploads/2013/02/w510-main-640x388.jpg"
    }
}
Run Code Online (Sandbox Code Playgroud)

似乎模型的属性没有通过更新parse.为什么不更新模型的属性?

u.k*_*u.k 6

您的代码也可能正常工作,但您没有正确测试它

你在调用this.fetch初始化方法.调用model.fetch是一个异步调用,当您尝试评估时mainModelInstance.attributes,http请求调用尚未完成.

你应该用以下方法测试:

var mainModelInstance = new MainModel();
mainModelInstance.on('change', function() {
  console.log(mainModelInstance.toJSON());
});
Run Code Online (Sandbox Code Playgroud)

甚至更好,不要自动获取initialize(它不是最好的做法)并使用jQuery承诺模式:

var mainModelInstance = new MainModel();
mainModelInstance.fetch().done(function () {
  console.log(mainModelInstance.toJSON());
});
Run Code Online (Sandbox Code Playgroud)