[英]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.