I've done some pub/sub using jQuery events.
Basic functionality works:
var publish = function(name) { // --- works
var args = Array.prototype.slice.call(arguments); // convert to array
args = args.slice(1); // remove arg1 (name)
$("html").trigger(name, args);
}
var subscribe = function(name, callback) { // --- works
$("html").on(name, callback);
}
var unsubscribe = function(name, callback) { // --- works
$("html").off(name, callback);
}
// usage: // --- works
var myhandler = function () { /* ... */ };
subscribe("foo", myhandler);
publish("foo", 1, false, "bob", {a:1, b:"2"});
unsubscribe("foo", myhandler);
But subscribing the way I want, does not:
var subscribe = function(name, callback) { // --- can't unsub this
$("html").on(name, function () {
var args = Array.prototype.slice.call(arguments);
args = args.slice(1);
callback.apply(null, args);
});
}
I want the second subscribe
function, as that anonymous callback strips the first argument (an Event
object) which I don't want in the "clean" client code. All I want to receive in the callback is the event data, I don't want Event object itself.
But this means that I cannot call unsubscribe
successfully, as I am not passing into off()
the same callback as passed into on()
- which was not the actual callback, but a wrapped anonymous function.
Is there a way around this?