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

Categories

0 votes
820 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...