-
-
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
Maybe a bug in model.get(), model.set() - maybe intention #2305
Comments
Update:
After this code, the |
@Paratron by re your first point about not sure what the solution is to avoid this confusion, maybe |
Hi @Paratron! This is definitely by design. Model#get is a fairly hot code path and thus shouldn't do any cloning. Model#toJSON, on the other hand, is used for persisting the model to the server. Besides having lesser performance requirements, it is generally assumed that data may be altered in Model#toJSON before being sent to the server. Such alterations are usually not done to data returned from Model#get, so no cloning is necessary. Edit: I'm assuming you meant Model#toJSON, not Model#getJSON. If not, please let me know. |
@moudy I am aware of the performance loss it will cause to clone every value returned by get but this way one does always have to be careful about what he's doing with the retrieved values... I think for the beginning, I am going to extend Backbone.Model with a method |
@Paratron - sounds like a good option - another option as I mentioned in #2315, would be to replace the Backbone.Model.prototype.toJSON = function () {
return JSON.parse(JSON.stringify(this.attributes));
};
Backbone.Model.prototype.get = function (key) {
var attrs = JSON.parse(JSON.stringify(this.attributes));
return attrs[key];
}; |
Hey,
I am not sure if this is happening by design or a bug.
I want to retrieve a value from a model, modify it and then set it back to the model, for example like so:
The problem is: since the value is returned by reference, my
members.push()
directly affects the content ofmymodel.attributes.members
.When I call the
mymodel.set()
, it won't trigger a change event, since it assumes that the model has already been changed.I would assume that .get() returns a clone of the model value to avoid unintended changes of the model. If this is the desired behavior, I would suggest to add a little notice in the docs of the
model.get()
function.The text was updated successfully, but these errors were encountered: