Sunday, July 21, 2013

Backbone custom events on model attribute change



In this article we are going to see how to handle custom events (i.e., when a model's value is changed, it should trigger an event.

Lets create a view called MessageView, it is attached to a model called MessageModel. Whenever anything happens on the web application, say an employee is saved successfully or there is an error saving an employee, it will update the messageModel.

In our scenario, whenever any attribute's value on MessageModel is changed, the view content should be changed.

       var Message = Backbone.Model.extend({
              defaults : {
                     message : "",
                     messageDetails : "",
                     messageType : ""
              },
       });

       var MessageView = Backbone.View.extend({
              el : '#message',
              initialize : function() {
                     this.model.on('change', this.render, this);
              },
              render : function() {
                     var templatewithMessage = _.template(MessageTemplate, this.model
                                  .toJSON());
                     $(this.el).html(templatewithMessage);
              }
       });


In this code, MessageTemplate is a template explained in the previous articles.

this.model.on('change') starts listening for any change events on this model and when someone changes an attribute in messageModel, it will fire, its corresponding function in our case, render method.

Hence the above code displays / updates the message in the message Bar. The message bar is nothing but a div represented by the id "message".

No comments:

Post a Comment