1

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

2 Answers 2

1

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)));
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.