backbone.js models pointing to same instance of nested model

后端 未结 2 1379
情书的邮戳
情书的邮戳 2020-12-29 14:24

Using backbone.js, here is a quick test to demonstrate the problem I am facing with nested models.

Preface I have a Obj Model that

相关标签:
2条回答
  • 2020-12-29 15:07

    With:

    var Obj = Backbone.Model.extend({
        defaults: {
            obj1    : new Obj1(),
            obj2    : new Obj2()
        }
    })
    

    You are saying that you want all objects created with "Obj" to have the same "obj1" and "obj2" values, use:

    var Obj = Backbone.Model.extend({
        initialize: function() {
            this.obj1 = new Obj1();
            this.obj2 = new Obj2();
        }
    });
    

    To achieve what you seen to want. http://documentcloud.github.com/backbone/#Model-constructor

    0 讨论(0)
  • 2020-12-29 15:10

    fortuneRice, when a Backbone model gets initialized, the super.constructor moves the defaults to the internal attributes array, where model.get looks for "obj1". Prusse's example initializes the obj1 and obj2 values with new objects for each instance, but doesn't move the values to the internal attributes array. Here is my modification of Prusse's solution.

    var Obj = Backbone.Model.extend({
        initialize: function() {
            myDefaults = {
                obj1: new Obj1();
                obj2: new Obj2();
            }
            this.set(myDefaults);
    });
    

    jQuery's extend method would combine the two objects. You could declare the non-object references with defaults and the object references with myDefaults in the initialize method.

    0 讨论(0)
提交回复
热议问题