Nyxynyx
Nyxynyx

Reputation: 63687

Setting the attribute values of a Model in backbone.js

I am learning backbone.js by following a tutorial. I tried out some code, and it appeared really strange. I first initialized a model instance with src being thesource.jpg, did a console.log of the model instance, then set the src attribute to aaa followed by a console.log.

In the javascript console, I see that for both outputs, the src is the same aaa. Shouldnt they be different?

JS Code

var Photo = Backbone.Model.extend({
   defaults: {
        src: 'placeholder.jpg',
        title: 'An image placeholder',
        coordinates: [0, 0]
    },

    initialize: function() {
        this.bind("change:src", function() {
            var src = this.get("src");
            console.log('Image source updated to ' + src);
        });
        console.log('This model has been initialized!');
    },

    changeSrc: function(source) {
        this.set({src: source});
    }
});

window.myPhoto = new Photo({title: "My awesomeness",
                        src: "thesource.jpg",
                        location: "Boston",
                        tags: ['big game', 'vacation']});

console.log(myPhoto.attributes);
myPhoto.set({src:'aaaa'});
console.log(myPhoto.attributes);

Console Output

enter image description here

Upvotes: 1

Views: 418

Answers (2)

loganfsmyth
loganfsmyth

Reputation: 161637

The answer above works, but I just want to point out that Backbone has functions that do basically this already. You can use toJSON, which clones all attributes and returns an object.

console.log(myPhoto.toJSON());
myPhoto.set({src: 'aaaa'});
console.log(myPhoto.toJSON());

This will show a shallow copy, so it's not quite the same, but it's less to type and would still work in the case you are looking for.

Upvotes: 1

Esailija
Esailija

Reputation: 140236

When you log objects in google chrome, their state is retrieved when you expand their properties in the console, not when you log them.

You can try to log a clone:

console.log(JSON.parse(JSON.stringify(myPhoto.attributes)));
myPhoto.set({src:'aaaa'});
console.log(JSON.parse(JSON.stringify(myPhoto.attributes)));

Upvotes: 1

Related Questions