-
-
Notifications
You must be signed in to change notification settings - Fork 5.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Collection Issue #3429
Comments
Hi @spyropress, please use the mailing list or StackOverflow for questions. Github issues are for maintaining the framework only. |
I think this is an issue as we cant use the default param for this....we have to use initialize function for model and set the property with new collection from there. as the Backbone is not cloning the default attributes and as JavaScript pass the value by reference. So, you have to clone the defaults as well.. |
It's hard to tell from this issue but it looks like you may be misunderstanding the way Javascript prototypes work. Here's an example to demonstrate: var Model = Backbone.Model.extend({
items: []
});
var a = new Model, b = new Model;
console.log(a.items, b.items); // [], []
a.items.push(1);
console.log(a.items, b.items); // [1], [1] Any references to objects stored on a prototype are shared amongst all of its instances. var Model = Backbone.Model.extend({
initialize: function() {
this.items = [];
}
});
var a = new Model, b = new Model;
console.log(a.items, b.items); // [], []
a.items.push(1);
console.log(a.items, b.items); // [1], [] |
Hi @akre54 , I have mention in my comment " as JavaScript pass the value by reference" which is same you mention "Any references to objects stored on a prototype are shared amongst all of its instances".. So, if I have a default attributes property in Backbone and I init two objects both have same reference, which is happening in the Example 1 So I think in the Model Constructor we should clone the defaults and then add it to the attributes. Thanks |
If you want to clone the defaults in initialize that's up to you. In general it's a bad idea to store objects on the prototype, and Backbone isn't going to help you with that. |
Sure there's similar precedent in other languages (such as everyones favourite gotcha: mutable default parameters in python), but I'd argue that this is in scope for BB to handle. For instance, competition such as Mootools will shallow clone objects on the Models prototype @spyropress you can make defaults a function and you won't run into this issue defaults() {
return {
data: []
};
} |
I have a Backbone App with 3 model which have nested collections:
Models Structure:
Now if I have two section model in layout and I go and add row model to one of the Section.rows collection, it is adding it to both sections.
BTW, I am adding it from a view on an event.
Thanks in Advance.
The text was updated successfully, but these errors were encountered: