[英]Function _.bind() won't bind an object
我具有延伸SugarCRM的视图类CreateView
,我想this
是this.model
在功能checkMonths
当字段starting_months_c
被改变,因此我可以输入this.get()
代替this.model.get()
/**
* @class View.Views.Base.DoVPCreateView
* @alias SUGAR.App.view.views.DoVPCreateView
* @extends View.Views.Base.CreateView
*/
({
extendsFrom: 'CreateView',
initialize: function(options) {
this._super('initialize', arguments);
// ....
this.model.on('change:starting_month_c', _.bind(this.checkMonths, this.model));
// ....
},
checkMonths: function() {
if (this.get('starting_month') == 12) {
// ....
}
}
不幸的是,这种构造不起作用。 我想知道,也许是因为.on()
函数以某种方式设置了上下文本身吗?
我在文档中发现,您可以将上下文作为第三个参数传递给函数
object.on(event, callback, [context])
我试过了,但是结果还是一样的-视图就是this
,而不是model
。
将上下文直接提供给.on
:
this.model.on('change:starting_month_c', this.checkMonths, this.model);
但这只是一个误导性的修复。 视图的功能都应该有this
作为视图实例,而不是其他任意对象。
// a simple example view var View = Backbone.View.extend({ initialize: function() { console.log("View init, month:", this.model.get('month')); // bind the context this.model.listenTo(this.model, "change:month", this.checkMonth); }, // the callback checkMonth: function() { // here, `this` is the model which you should NOT do. // but for demonstration purpose, you can use `this.get` directly. console.log("checkMonth:", this.get('month')); }, }); // sample for the demo var model = new Backbone.Model({ month: 2 // dummy value }), view = new View({ model: model }); console.log("change month"); model.set({ month: 3 // set to trigger the callback });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
如果在该模型的任何实例中,无论starting_month_c
何时发生更改,如果您始终希望触发检查“ months”回调,则可以将其移入模型类本身。
var Model = Backbone.Model.extend({
initialize: function() {
// favor listenTo over `on` or `bind`
this.listenTo(this, 'change:starting_month_c', this.checkMonths);
},
checkMonths: function(model, value, options) {
if (this.get('starting_month') === 12) {
// whatever you want
}
}
});
如果仅用于此特定视图, this.model.get
在回调中使用this.model.get
。 这不是问题,这是标准的做法。
有关为何偏爱listenTo
更多信息。
也许上下文比this.model更重要:
.bind(this.checkMonths, this)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.