Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
806 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...