Fez Vrasta
Fez Vrasta

Reputation: 14835

jQuery plugin to extend on() function doesn't accept "this"

I'm writing a plugin to extend the on() function of jQuery to implement mousetrap.js

I should get from the function this and pass it to on().

This is my code:

    $.fn.superon = function (keys, myfn) {
        $("body").on("click", this, function (e) {
            myfn();
        });
        Mousetrap.bind(keys, function () {
            myfn();
        });
    };
    $.fn.superoff = function (keys) {
        $("body").off(this);
        Mousetrap.unbind(keys);
    };

The problem is that if I use it the event is attached to all the elements and not only the one selected.

http://jsfiddle.net/zkLMX/1/

What am I doing wrong?

Upvotes: 0

Views: 109

Answers (3)

jsist
jsist

Reputation: 5253

  1. You are missing event type "click" in .off function.
  2. Second argument to .on function in your case has to be selector (what you are passing is jQuery object)

Following is the updated code

(function ($) {
    $.fn.superon = function (selector, keys, myfn) {
        $("body").on("click", selector, function (e) {
            myfn();
        });
        Mousetrap.bind(keys, function () {
            myfn();
        });
        return this;
    };
    $.fn.superoff = function (selector, keys) {
        $("body").off("click", selector);
        Mousetrap.unbind(keys);
        return this;
    };
})(jQuery);


$("#click").superon("#click", "a", function () {
    alert("hello");
    $("#click").superoff("a");
});

});

$("#click2").superon("#click2", "b", function () {
    alert("hello2");
    $("#click2").superoff("b");
});

Hope it helps...

Upvotes: 1

devnull69
devnull69

Reputation: 16544

The second parameter to .on() is a selector string, not an element. You should just omit the second parameter and bind the click to this instead of body

$.fn.superon = function (keys, myfn) {
    this.on("click", function (e) {
        myfn();
    });
    Mousetrap.bind(keys, function () {
        myfn();
    });
};
$.fn.superoff = function (keys) {
    this.off("click");
    Mousetrap.unbind(keys);
};

http://jsfiddle.net/zkLMX/4/

Upvotes: -2

Fez Vrasta
Fez Vrasta

Reputation: 14835

This is my solution, thanks for the suggestion of @devnull69.

 // on() with keyboard shortcut support
 $.fn.superon = function (selector, keys, myfn) {
   this.on("click", selector, function (e) {
     myfn();
   });
   Mousetrap.bind(keys, function () {
     myfn();
   });
   return this;
 };

 // off() with keyboard shortcut support
 $.fn.superoff = function (selector, keys) {
   this.off("click", selector);
   Mousetrap.unbind(keys);
   return this;
 };

In this way I will call this in the same way of how I would call the on() and off() functions.

Upvotes: 0

Related Questions