0

I'm trying to make my jQuery code more readable and easier to maintain.

Here's what I have :

var module = {
    init: function () {
        this.domElement       = $('#dom_element');
        this.secondDomElement = $('#second_dom_element');
        this.okElement        = 'ok';
        this.events();
    },

    events: function () {
        this.domElement.on('click', $.proxy(this.alertOk, this));
        this.secondDomElement.on('click', $.proxy(this.alertOkAndItSelf, this));
    },

    alertOk: function () {
        alert(this.okElement);
    },

    alertOkAndItSelf: function () {
        alert(this.okElement + ' ' + $(this)); // $(this) != $('#second_dom_element') !
    }
};

So when module.domElement is clicked, that works fine. 'ok' is in the alert.

But when module.secondElement is clicked, 'ok' is in the alert, but then $(this) is still referencing the module. If I don't use $.proxy, then this is the current element, but how do I access the okElement property of module ?

I feel like using module.okElement to access it is kind of dirty.

Steve Chamaillard
  • 2,289
  • 17
  • 32

0 Answers0