Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add a customized property for jQuery event object?

Sample code is as following:

$('a').mousedown(function(event)
   {
            event.ABC = true;

   });

$(window).mousedown(function(event)
    {
        console.log("event.ABC:",event.ABC);
         //outputs "undefined "

        if( event.ABC)
        {
          // do sth
        } 
        else
        {
            //let it go  
        }


    });
like image 471
Bobo Avatar asked Dec 22 '22 07:12

Bobo


2 Answers

Others have mentioned that the jQuery event gets recreated for each callback, which is why any attribute you add to the jQuery event is lost.

However, the jQuery event has an originalEvent attribute which does persist through the entire event propagation phase.

Instead of event.ABC, you can just do event.originalEvent.ABC.

Note: If you intend on using this extensively, you may want to add a myAppData attribute to store all your data in, i.e. event.originalEvent.myAppData.ABC. This makes it easy to identify which event attributes are your custom ones and also reduces the possibility of name collisions.

like image 159
user3092682 Avatar answered Jan 05 '23 22:01

user3092682


Though I'm not sure exactly what you want to do, I'm guessing it would be a lot easier if you didn't have to mess with the events object. Just set up a flag variable when your <a>'s are clicked:

var eventABC = false;

$('a').mousedown(function() {
        eventABC = true;
});

$(window).mousedown(function() {
    console.log("eventABC:", eventABC);
    //outputs true if <a> clicked, false otherwise

    if(eventABC) {
      // do sth
    } else {
        //let it go  
    }

    eventABC = false;
});

But you can trigger events in jQuery. Like so:

$('a').click(function() {
    $(window).trigger("eventABC", ['CustomProperty1', 'CustomProperty2']);
    return false;
});

$(window).bind('eventABC', function(event, param1, param2) {
    alert("eventABC triggered: " + param1);
});
like image 41
uɥƃnɐʌuop Avatar answered Jan 05 '23 23:01

uɥƃnɐʌuop