简体   繁体   中英

Backbone.js event trigger

How to bind a change event to model from view to change name and display the changed name in view block.

Student = Backbone.Model.extend({
    initialize: function(){
        this.on("change:name", function(model){
            var name = model.get("name");
            alert("Changed my name to " + name );
        });
    }
});

var pe = new Student({ name: "sinduja", age: 20});
pe.set({name: 'shalini'});

Doesn't backbone trigger change events automatically on model.set ?

You just have to register your view to the change event.

Student = Backbone.Model.extend({
    initialize: function(){
        //initialize variables
    }
});

StudentView = Backbone.View.extend({
    initialize: function(model) {
        _.bindAll(this);
        model.on("change:name",this.nameChanged)
    },
    nameChanged: function(evt) {
        console.log("name changed", evt)
    }

})

Usage:

var pe = new Student({ name: "sinduja", age: 20});
var sv = new StudentView(pe);
pe.set({name: 'shalini'});

I used to write my own custom stuff for reacting to bi-directional model/view changes, which is a bit of a maintenance pain. Then I found the plugin Backbone.ModelBinder .

It makes what you want to achieve stupidly easy. There are some good examples on the github readme page I linked you to so there's no point me giving any! If it seems a bit confusing at first I would say try your best to get it working as in the long run this plugin will save you countless hours, like it has for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM