Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js: How do you call a View's "method" from outside the View's scope (e.g: inside a model's validation handler)

Basically, I'm trying to do something like this:

Person = Backbone.Model.extend({

   validate: { ... },

   initialize: function(){ 
      this.bind('error', ?......?); <== what do I put?
   },

   // I DON'T WANT TO CALL THIS ONE
   handleError: function(){ }

});


ViewOne = Backbone.View.extend({

   //I WANT TO CALL THIS ONE:
   handleError: function(model, error){ 
         //display inside segmented view using jQuery 
   };

});

I tried options.view.handleError but it doesn't work...

My main purpose: I want a specific View that created the model to handle the error, not have the model to globally handle it all. For example, I want View#1 to do an alert while I want View#2 to display in a div. I don't know if this is the right way of doing it. If not, I would be gladly accept your help.

Thank you.


UPDATE: here's my jsFiddle http://jsfiddle.net/jancarlo000/87mAk/

like image 818
Jan Carlo Viray Avatar asked Jan 24 '26 06:01

Jan Carlo Viray


1 Answers

Since Backbone 0.5.2 it is recommended to drop bindAll in favor of third argument to bind if you need to pass the context.

ViewOne = Backbone.View.extend({
    initialize: function() {            
        this.model.on('error', this.handleError, this);
    },
    handleError: function(model, error) { /* ... */ }
});
...
var person = new Person();
var viewone = new ViewOne({model : person});

General note here is that Models should never know about their Views. Only Views should subscribe to Model events.

like image 117
opengrid Avatar answered Jan 25 '26 21:01

opengrid