Brian DiCasa
Brian DiCasa

Reputation: 9487

jQuery - using $(this) in custom function

I'm trying to create a custom function that unbinds and then binds an event. It looks like this:

App.bindEvent = function(selector, eventType, eventHandler) {
    $(selector).unbind(eventType);
    $(selector).bind(eventType, function(event) {
        eventHandler(event);
    });
};

However, the problem I am facing is that I cannot use the this keyword to reference the DOM element that was clicked. For example, I cannot do this:

App.bindEvent("#my-element", "click", function() {
    var myId = $(this).attr("data-my-id");
});

How would I go about getting the this keyword to point to the clicked DOM element like it does in jQuery.bind()?

Thanks for any help.

Upvotes: 1

Views: 222

Answers (4)

Eli
Eli

Reputation: 17825

How about this instead:

App.bindEvent = function(selector, eventType, eventHandler) {
    var element = this;

    $(selector).unbind(eventType);
    $(selector).bind(eventType, function(event) {
        eventHandler.call(element, event);
    });
};

Upvotes: 2

Joseph
Joseph

Reputation: 25523

I think you're trying to refer to

event.target

For example:

App.bindEvent("#my-element", "click", function(event) {
    var myId = $(event.target).attr("data-my-id");
});

check out jquery's event documentation

Upvotes: 0

Jerod Venema
Jerod Venema

Reputation: 44632

Change:

eventHandler(event);

To:

eventHandler.call(this, event);

That'll change the "scope" of your function to be the same as the scope of the original "bind" call.

Upvotes: 3

SLaks
SLaks

Reputation: 887451

You need to call the handler in the context of the object:

eventHandler.call(this, event);

Upvotes: 1

Related Questions