Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript pseudo-classes, jQuery event handlers and 'this'

I've got a big Javascript project that I'm trying to refactor into pseudo-classes:

jsFiddle: http://jsfiddle.net/waitinforatrain/7T42w/

var MyNameSpace = {}

MyNameSpace.MyClass = function() {
    this.doSomething = function () {
        return "hello";
    }

    this.doSomething2 = function() {
        var x = this.doSomething() + " world";
        alert(x);
    }

    this.doSomething2(); //Works fine

    $("#mydiv").click ( this.doSomething2 ); //Doesn't work
}

var class = new MyNameSpace.MyClass();

The reason the click event causes an error is that this refers to the #mydiv element.

How am I supposed to design the above so that I can access the element that was clicked but can also call doSomething()?

like image 825
bcoughlan Avatar asked Dec 09 '25 23:12

bcoughlan


2 Answers

You need to cache the context reference and wrap the call in a closure:

var MyNameSpace = {}

MyNameSpace.MyClass = function() {
    var context = this;

    context.doSomething = function () {
        return "hello";
    }

    context.doSomething2 = function() {
        var x = context.doSomething() + " world";
        alert(x);
    }

    // You can do this:
    context.doSomething2();

    // Or this:
    $("#mydiv").click(function(e) {
        context.doSomething2();
    });
}
like image 188
Eli Avatar answered Dec 11 '25 12:12

Eli


this.doSomething2 = $.proxy(function() {
    var x = this.doSomething() + " world";
    alert(x);
}, this);

$.proxy binds the this scope to the context variable inside said function.

like image 41
Raynos Avatar answered Dec 11 '25 11:12

Raynos