The spine listens for changes to an object in the model

Can I listen to any changes to one object in the model? I know how to listen to model changes, but I only need to listen to objects in the 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';
    }
})

      

+3


source to share


2 answers


This is exactly what the models are for, not just fetching data from the server, but also passing data around your application.

When you want to be informed about changes to some data, you are not creating a custom variable that uses 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/

+9


source


you can listen for model 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
       });
    }

      

0


source







All Articles