![](/img/trans.png)
[英]Javascript callback function throws error “Callback is not a function” in firefox
[英]Trying to bind a callback by passing in the function throws an error
我只想在輸入使用jQuery 1.7.2和Backbone.js更改值時觸發事件。
目前我有以下(有效)
MyView: Backbone.View.extend({
initialize: function() {
this.colorInput = $("<input />", {
"id": "color",
"name": "color",
"value": this.model.get("color")
});
var self = this;
this.colorInput.on("change", function() {
self.changeColor();
});
},
changeColor: function() {
var color = this.colorInput.val();
this.model.set("color", color);
}
});
我正試圖通過我的功能傳遞另一種方式。
this.colorInput.on("change", this.changeColor, this);
但是當試圖這樣做時,它會拋出錯誤
((jQuery.event.special [handleObj.origType] || {})。handle || handleObj.handler).apply不是函數
.apply(matched.elem,args);
( 第3332行 )
我無法弄明白。 任何想法為什么這種方式不起作用?
你混淆jQuery的on
:
.on(events [,selector] [,data],handler(eventObject))
.on(events-map [,selector] [,data])
與Backbone on
:
object.on(event,callback,[context])
Backbone將上下文作為第三個參數,jQuery沒有。 看起來像jQuery的on
是解釋第三個參數作為handler(eventObject)
,並試圖把它像一個功能,這可以解釋你所看到的錯誤消息。
通常你會這樣做:
MyView: Backbone.View.extend({
events: {
'change input': 'changeColor'
},
initialize: function() {
this.colorInput = $("<input />", {
"id": "color",
"name": "color",
"value": this.model.get("color")
});
},
render: function() {
this.$el.append(this.colorInput);
return this;
},
changeColor: function() {
var color = this.colorInput.val();
this.model.set("color", color);
}
});
讓Backbone的事件委托系統處理好事情。
這適用於遇到此問題的Google員工。 我有這個完全相同的問題,發生的事情是報告錯誤的地方和實際發生的錯誤位於兩個不同的地方。
一行代碼已過時,看起來像
$('#modal').on('click', function(e) {
// Execute invalid code here.
});
另一行代碼類似:
$('#modal').on('click', function(e) {
// Execute valid code here.
});
錯誤是第一次調用不是一個真正的函數,所以錯誤是准確的,被調用的第二個處理程序不是一個真正的函數,jQuery無法完成它,但它總是表現得好像它發生在第二個函數調用上。
我會說如果你遇到這個錯誤,刪除任何可能被觸發的額外事件處理程序,看看是否能解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.