backbone listen to object changes in model

2019-07-01 19:59发布

Can I listen to any changes in one object in Model? I know how to listen model changes, but I need only to listen objects in model and view.

var view = Backbone.View.extend({
    func: {},
    initialize: function () {
        this.listenTo(this.func, 'change', function(select){
            console.log(select.changed) //NEED TO SHOW ON ADDING ANY DATA TO this.func
        })
        this.func['asd'] = 'asdasd';
    }
})

2条回答
Luminary・发光体
2楼-- · 2019-07-01 20:39

This is exactly what models are for - not just fetching data from a server but also passing data around your app.

When you want to be informed about changes to some data you don't create a custom variable you use attributes.

var MyModel = Backbone.Model.extend({
    initialize: function() {
        // Listen to changes on itself.
        this.on('change:asd', this.onAsdChange);    
    },

    onAsdChange: function(model, value) {
        console.log('Model: Asd was changed to:', value);
    }
});

var MyView = Backbone.View.extend({
    initialize: function() {
        // Listen to changes on the model.
        this.listenTo(this.model, 'change:asd', this.onAsdChange);  
    },

    onAsdChange: function(model, value) {
        console.log('View: Asd was changed to:', value);
    }
});

var myModel = new MyModel();
var myView = new MyView({
    model: myModel
});

myModel.set('asd', 'something');

myModel.set('asd', 'something else');

Fiddle: http://fiddle.jshell.net/ferahl/4fxtZ/

查看更多
叛逆
3楼-- · 2019-07-01 20:39

you can listen to model's change event using

    initialize: function(){
       this.listenTo(this.model, 'change',  function(select){
             console.log(select.changed) //NEED TO SHOW ON ADDING ANY DATA TO this.func
       });
    }
查看更多
登录 后发表回答