Search code examples
javascriptbackbone.js

What is `this` inside a Backbone model?


I'm learning some Backbone and I'm confused as to what this is inside of the model.

Person = Backbone.Model.extend({
    initialize: function() {
        console.log('hello world');
        this.bind("change:name", function() {
            console.log(this.get('name') + " is now the value for name");
        });
        this.bind('invalid', function( model, error ) {
            console.error(error);
        });
    },
    defaults: {
        name: "Bob Hope",
        height: "unknown"
    },
    validate: function ( attributes ) {
        if( attributes.name == 'Joe' ) {
            return "Uh oh, you're name is Joe!";
        }
    }
});
var person = new Person();
person.set({name: "Joe", height:"6 feet"}, {validate:true});
console.log(person.toJSON());

What is going on in this.bind? What is change:name? Are initialize and defaults simply just methods inside of a javascript object?


Solution

  • this inside initialize is the instance of the model.

    .bind is an alias for .on method inside backbone.Events module which allows you to bind event handlers on an object

    change:name is just the event name, it allows you to track changes of a model's attribute named 'name'.

    initialize is a constructor method which will be called initially when you instantiate the model.

    defaults is an object (or it can be a function) that sets default model attributes.

    So initialize and defaults are indeed methods inside an object (except that defaults can be also a property), but they have special meaning for backbone. And that object is extended with all other methods and properties of Backbone.Model which makes it a functional model.

    read more in backbone docs