1

Maybe I am missing something, but I can't figure out how can I call one of the methods of the Listviewclass from the click callback.

Here's the code:

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

1 Answer 1

6

You have several options:

  1. Since you're defining your click handler function inline anyway, use a local variable your handler closes over:

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

    this.element.find('li').click($.proxy(function (e) {
        // `this` is your instance, `e.currentTarget` is the element
        this.selectElement(e.currentTarget);
    }, this));
    
  3. Use ES5's Function#bind:

    this.element.find('li').click(function (e) {
        // `this` is your instance, `e.currentTarget` is the element
        this.selectElement(e.currentTarget);
    }.bind(this));
    
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.