1

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.

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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);
    });
};

Comments

1

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

eventHandler.call(this, event);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.