Reputation: 14835
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.
What am I doing wrong?
Upvotes: 0
Views: 109
Reputation: 5253
"click"
in .off
function. .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
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);
};
Upvotes: -2
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