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

sim*_*neL 1 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);
};
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 6

你有几个选择:

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

    var inst = this;
    this.element.find('li').click(function () {
        // `inst` is your instance, `this` is the element
        inst.selectElement(this);
    });
    
    Run Code Online (Sandbox Code Playgroud)
  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));
    
    Run Code Online (Sandbox Code Playgroud)
  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));
    
    Run Code Online (Sandbox Code Playgroud)