providing new collection in “defaults” backbone.js

2019-08-14 07:49发布

问题:

im new to backbone js and my first interaction seems pretty comple. the problem goes like this
i have made a model like this

window.Dir = Backbone.Model.extend({
                defaults: { 
                  "Name": "", 
                  "ChildNodes": new window.FSNodeCollection() },
                GetFullName: function () { this.get("id"); }
            });

window.FSNodeCollection is some other collection that i have made. as you will notice i have put the value of ChildNodes attribute to new window.FSNodeCollection()

this according to what i have read should set the value of ChildNodes to a new window.FSNodeCollection()
but when im using this model like

var fsNode = new window.FSNode({
                Type: "dir",
                Node: new window.Dir({
                    Name: "dir1",
                })
            });
var fsNode2 = new window.FSNode({
                Type: "dir",
                Node: new window.Dir({
                    Name: "dir2",
                })
            });
var subDir1Node = new window.FSNode({
                Type: "dir",
                Node: new window.Dir({
                    Name: "subDir1",
                    ChildNodes:new window.FSNodeCollection()
                })
              });
            fsNode.get("Node").get("ChildNodes").push(subDir1Node);

the subDir1Node is being added to the ChildNodes of both fsNode and fsNode2
what am i doing wrong?

when i try doing something like this

var fsNode = new window.FSNode({
                Type: "dir",
                Node: new window.Dir({
                    Name: "dir1",
                    ChildNodes:new window.FSNodeCollection()
                })
            });
var fsNode2 = new window.FSNode({
                Type: "dir",
                Node: new window.Dir({
                    Name: "dir2",
                    ChildNodes:new window.FSNodeCollection()
                })
            });
var subDir1Node = new window.FSNode({
                Type: "dir",
                Node: new window.Dir({
                    Name: "subDir1",
                    ChildNodes:new window.FSNodeCollection()
                })
              });
            fsNode.get("Node").get("ChildNodes").push(subDir1Node)

the problem remains no more.

回答1:

The problem is that they are both referencing the same array, what you need to do is make sure that when you create your model you initialize your array at that point (you can use the initialize method or you can assign a function that will assign the collection).

You might want to take a look at these questions

Arrays in a Backbone.js Model are essentially static?

Why do new instances of a Backbone.js model contain additional values to the predefined defaults?