【问题标题】:Backbone JS - JSON response recognized as actual Backbone modelBackbone JS - JSON 响应被识别为实际的 Backbone 模型
【发布时间】:2012-07-06 19:49:11
【问题描述】:

我正在使用带有一些嵌套模型的主干。我在父模型和子模型上有一堆用于 UI 更新的更改处理程序(下面的简化版本)。我遇到的问题是,只要我在父模型上调用 save() 并且 JSON 从服务器返回,子模型数据就会更新,但它不再被识别为主干模型,并且我的处理程序都失败了.

ChildModel = Backbone.Model.extend({
    defaults: {
        property: "property"           
    }
});

ParentModel = Backbone.Model.extend({
    defaults: {
        childModel: new ChildModel()           
    },
    url : "resturl",
    initialize: function () {
        this.bind('change:childModel', this.changeHandler, this);
    },             
    changeHandler: function () {
       var child = this.get('childModel');
       if(child instanceof Backbone.Model){
         alert("is a backbone model");
       } else {
         alert("is not a backbone model")
       }
    }
});

var parent = new ParentModel();
parent.save()

当调用 parent.save() 时,模型会更新,但“不是主干模型”会收到警报。 ​

【问题讨论】:

    标签: backbone.js


    【解决方案1】:

    查看我对您的other 问题的回答。我认为这是相关的:

    https://stackoverflow.com/a/11368225/737318

    如果这没有帮助,请告诉我。

    【讨论】:

    • 谢谢蒂姆。我明天会深入研究这个,让你知道我的进展情况!
    【解决方案2】:

    考虑重写 parse 方法并在此处而不是在其他地方更新 childModel。方法。这适用于保存模型更新的绑定事件。

    parse: function ( response, xhr ) {
        // don't update the models childData attribute
        if ( this.get('childModel') instanceof ChildModel ) {
    
            this.get('childModel').set( response.childData );
        } else {
           this.set({ childModel: new childModel( response.childData );
        }
        delete response.childData;
        return response;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 2015-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多