3

One example in codeschool's backbone.js tutorial has the following solution:

Application.js

var appointment = new Appointment({id: 1});

appointment.on('change',function() {
  alert('its changed');
});

I realize this is probably a simplified example but in most cases wouldn't you want this defined on the model definition so it applies to all model instances?

Something in the model definition that says whenever an instance of me changes fire this method in the view? That view method could then fire the alert.

I'm obviously just learning so any help is appreciated!

turbo2oh
  • 2,849
  • 6
  • 34
  • 46

1 Answers1

1

Here the event is attached to that particular model instance. So the same will not trigger an event for any other instance..

var appointment = new Appointment({id: 1}); <--- Event is triggered

var appointment1 = new Appointment({id: 2}); <--- Event is not triggered

appointment.on('change',function() {
  console.log('its changed');
});

Since the event is attached directly on the instance of the model. But if you do the same when defining the Model, it would trigger the same on all the instances of the Model.

var Appointment = Backbone.Model.extend({
     initialize: function() {
         this.on('change', function() {
             console.log('its changed')
         });
     }
}); 

Now any change on the instance of the model will trigger an event.

var appointment = new Appointment({id: 1}); <--- Event is triggered

var appointment1 = new Appointment({id: 2}); <--- Event is triggered

If you talking about the same on a View, then the model that is passed to the instance will generally keep listening to the event. And if there is any change then a method will be invoked changing the state of the view.

var View = Backbone.View.extend({

     initialize: function() {
         // Listening to the event on the model which when 
         // triggered will render the view again
         this.listenTo(this.model, 'change', this.render);
     },
     render: function() {

         // do something
     }
});

var view = new View();

view.render();
Sushanth --
  • 55,259
  • 9
  • 66
  • 105