I'm working on developing a rather lightweight realtime application.
We're using jQuery's event system to talk between modules in our application. So everything that makes changes in the DOM that should affect anything outside the module must do so by events.
These events are caught by a clientside socket.io implementation which asks the nodejs socket.io server to broadcast the events to all other clients.
MY QUESTION: Is there a way figure out on what selector the event was triggered? So that if I call
$("tag.class").trigger("myevent");
I can somehow do
$(document).on("myevent", function() {
console.log(this.selector)
});
And it will print "tag.class"
This is interesting because it would be interesting to know that a user triggered a certain event on a selection, rather than a certain event on a number of elements which might appear quite random afterwards.
I have read this question but I wish to be able to get the selector on all events fired in the application.
Thank you for your time :)
Taking inspiration from the linked answer, you can override the jQuery trigger
function. Something like:
$.fn.origTrigger = $.fn.trigger;
$.fn.trigger = function (fn) {
var selector = this.selector;
this.origTrigger(function (ev) {
fn(ev, selector);
});
};
Your best bet is to send data with the event. It is also more robust, as you have more control. Selectors might not be pretty, but the data are.
$('tag.class').trigger('myevent', ['some', 'param']);
$(document).on('myevent', function(param1, param2) {
console.log(param1); // "some"
console.log(param2); // "param"
});
Of course, if you want to send as many parameters as you want, you can use an "options" object and handle it in such a way:
$('tag.class').trigger('myevent', [{some: 'option', other: 'option'}]);
$(document).on('myevent', function(options) {
var opts = {
default: 'option',
some: 'default',
other: 'default'
};
$.extend(opts, options);
console.log(opts); // {default: "option", some: "option", other: "option"}
});