styler
styler

Reputation: 16501

Why do I always need to clone model attributes in Backbone?

I'm overriding the Backbone Model toJSON to reformat some data, I see _.clone() a lot and I've seen that I need to clone this.attributes. I'm not completely sure why I need to clone, can anyone explain?

JS

toJSON: function()
    var attributes = _.clone(this.attributes);

    //...
}

Upvotes: 0

Views: 79

Answers (1)

T J
T J

Reputation: 43156

Since objects are passed by reference in ,

If you do this:

var attributes = this.attributes;

Whatever changes you make to attributes will reflect in the actual model as well.

Most of the time this is not the desired behavior, hence the use of _.clone or similar utility methods

Upvotes: 1

Related Questions