简体   繁体   English

Backbone.js:如何从View的范围外调用View的“方法”(例如:在模型的验证处理程序内)

[英]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... 我尝试了options.view.handleError但它不起作用......

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. 我的主要目的:我想要一个特定的View创建模型来处理错误,而不是让模型全局处理它。 For example, I want View#1 to do an alert while I want View#2 to display in a div. 例如,我希望View#1在我希望View#2显示在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/ 更新:这是我的jsFiddle http://jsfiddle.net/jancarlo000/87mAk/

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. 从Backbone 0.5.2开始,如果需要传递上下文,建议删除bindAll以支持第三个绑定参数。

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

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM