最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Backbone.js: How do you call a View's "method" from outside the View's scope (e.g

programmeradmin0浏览0评论

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) { /* ... */ }

});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论