FeR-S FeR-S - 7 months ago 33
Javascript Question

Document event ID

I need to identify specific event on the document in events object. For example

$(document).click(function () {
console.log(1)
});

$(document).click(function () {
console.log(2)
});

var events = $._data(document, "events");
console.log(events);


enter image description here

And when i log all "click" events, there are no difference between it:

How can i add custom ID to each events? Maybe i can use namespace or i can change guid?

I need to check: "is the specific event exist?"

Answer Source

You can bind and pass argument to the call-back listener to identify the type

$(document).click(function (type) {
      console.log(type)
}.bind(this,"i-am-click"));

$(document).click(function (type) {
      console.log(type)
}.bind(this,"i-am-another-click"));

var events = $._data(document, "events");
console.log(events);

UPDATE

To Identify the specific event object in yours events array you can do the following hack.

 $(document).click(
    (function(){
        var fn = function(){  // Your callback function
                      console.log('i-am-click');
                 };

        fn.event_id=1;  // Adding id to the callback.

        return fn;  // returning the function after adding id
    })()
);

$(document).click(
    (function(){
        var fn = function(){  // Your callback function
                      console.log('i-am-another-click');
                 };

        fn.event_id=2;  // Adding id to the callback.

        return fn;  // returning the callback function after adding id
    })()
);

var events = $._data(document, "events");

// Find the events in the event array using filter

// This will return an array of match event with id in events array
events.click.filter(function(ev){return ev.handler.event_id==1;}); // event id you are looking for