也许我遗漏了一些东西,但我无法弄清楚如何从点击回调中调用Listviewclass的方法之一。
以下是代码:
function Listview(el, cb) {
this.element = el;
this.callback = cb;
this.select = function (element, index) {
...
};
this.selectElement = function (element) {
...
};
this.unselectCurrentElement = function () {
...
};
this.element.find('li').click(function () {
// Here I want to call for example the selectElement method
// but how?
// The This keyword reference the "li" element
});
this.element.addClass("Listview");
this.select(this.element, 0);
};
答案 0 :(得分:6)
您有几种选择:
由于您无论如何都要内联定义click
处理函数,请使用处理程序关闭的局部变量:
var inst = this;
this.element.find('li').click(function () {
// `inst` is your instance, `this` is the element
inst.selectElement(this);
});
使用jQuery' proxy
:
this.element.find('li').click($.proxy(function (e) {
// `this` is your instance, `e.currentTarget` is the element
this.selectElement(e.currentTarget);
}, this));
使用ES5' Function#bind
:
this.element.find('li').click(function (e) {
// `this` is your instance, `e.currentTarget` is the element
this.selectElement(e.currentTarget);
}.bind(this));