我试图从jquery事件处理程序调用原型方法。我有这样的代码:
$('#' + this.ID + ' .selMake').on('change', this.getCarModel());
我收到一条错误消息: 未捕获的TypeError:对象[object global]没有方法' getCarModel'
我在这里做错了什么?
答案 0 :(得分:1)
您需要做的第一件事是从函数中删除括号。您的代码当前期望的是getCarModel
返回一个函数,然后在触发事件时调用该函数。
看起来这就是你想做的事情:
$('#' + this.ID + ' .selMake').on('change', that.getCarModel);
不是这个:
$('#' + this.ID + ' .selMake').on('change', that.getCarModel());
如果您想以这种方式调用该函数,您可以执行以下操作:
var that = this;
$('#' + this.ID + ' .selMake').on('change', function () {
that.getCarModel();
});
上面,你传递一个匿名函数作为参数,它将执行它内部的代码。
在上面的函数中,this
的定义将取决于触发事件的元素。如果您希望将this
的定义与您的this
对象绑定,则可以执行以下操作:
最简单易懂的方法是使用that
变量:
var that;
$('#' + this.ID + ' .selMake').on('change', that.getCarModel); // This will execute the function this.getcarModel
您还可以在支持ES5的浏览器中使用bind
方法。
$('#' + this.ID + ' .selMake').on('change', this.getCarModel.bind(this));
答案 1 :(得分:1)
.on()
的第二个参数应该是一个函数。您在绑定处理程序时调用该函数,而不是在事件发生时调用该函数。它应该是:
var self = this;
$('#' + this.ID + " .selMake').on('change', function() {
self.getCarModel();
});
您需要使用局部变量self
,因此this
将保存在闭包中。参见
"this" keyword in event methods when using JavaScript prototype object
了解详情。
答案 2 :(得分:0)
使用此代码:
vehicleSelect.prototype.getCarMakes = function() {
// Optional parameters
var options = {};
var select = $('#' + this.ID + ' .selMake'),
that = this;
select.on('change', function(e) {
that.getCarModel();
});
// Callback function to be called when the API response is returned
function success(res) {
for (var i=0; i<res.makes.length; i++) {
$("<option>",{
value: res.makes[i].niceName,
html: res.makes[i].name
}).appendTo(select);
}
select.removeAttr("disabled");
select + $(' option[value="placeholder"]').html('Select Make');
}
// Oops, we have a problem!
function fail(data) { console.log(data); }
// Fire the API call
this.res.api('/api/vehicle/v2/makes', options, success, fail);
};
为什么您不能使用select.on('change', this.getCarModel)
,请参阅this question(也提供其他解决方案)。