如何从jquery回调中调用对象方法

时间:2014-08-31 15:53:45

标签: javascript jquery object

也许我遗漏了一些东西,但我无法弄清楚如何从点击回调中调用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);
};

1 个答案:

答案 0 :(得分:6)

您有几种选择:

  1. 由于您无论如何都要内联定义click处理函数,请使用处理程序关闭的局部变量:

    var inst = this;
    this.element.find('li').click(function () {
        // `inst` is your instance, `this` is the element
        inst.selectElement(this);
    });
    
  2. 使用jQuery' proxy

    this.element.find('li').click($.proxy(function (e) {
        // `this` is your instance, `e.currentTarget` is the element
        this.selectElement(e.currentTarget);
    }, this));
    
  3. 使用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));