admin管理员组

文章数量:1310203

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 /

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/jancarlo000/87mAk/

Share Improve this question edited Jan 24, 2012 at 7:43 JC JC asked Jan 24, 2012 at 4:26 JC JCJC JC 12.1k11 gold badges44 silver badges63 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

Since Backbone 0.5.2 it is remended 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.

You have it backwards, the view should be binding to the model's events:

ViewOne = Backbone.View.extend({
    initialize: function() {
        _.bindAll(this, 'handleError');
        this.model.bind('error', this.handleError);
    },

    handleError: function(model, error) { /* ... */ }

});

本文标签: