Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jQuery objects as parameters for the delegate method

Multiple selectors are used with delegate using the following:

$(contextElement).delegate('selector1, selector2' , 'eventName', function(){ //blabla });

In larger projects where managing DOM elements becomes crucial, storing the elements in variables that are binded to the window object becomes an attractive way to work.

However I can't join this way of working with using multiple selectors on the delegate method:

window.someControl = {
     contextElement = $('selector0'),
     DOMasProperty1 = $('selector1'),
     DOMasProperty2 = $('selector2')
}

someControl.contextElement.delegate(
'you magic answer for using DOMasProperty1 
and DOMasProperty2', 
'click', 
function(){ 

  //blabla 

});

Note: I am aware that the string value of the selector as oppose to its jQuery object can be stored in the someControl object. However I am storing the jQuery objects to improve the performance of the code and simply calling the string values over and over again will make this way of working not different to simply using the selector name wit the method.

I need an answer to somehow combine the use of delegate with reducing DOM lookups

like image 790
Ali Habibzadeh Avatar asked Aug 01 '26 23:08

Ali Habibzadeh


2 Answers

jQuery objects have a .selector property that will refer to your original selector.

someControl.contextElement.delegate(
    window.someControl.DOMasProperty1.selector + ',' + 
    window.someControl.DOMasProperty2.selector,
    'click', 
    function(){ 

          //blabla 

    });

Note that it will work for:

DOMasProperty1 = $('selector1'),

...but probably not if you include DOM traversal methods like:

DOMasProperty1 = $('selector1').parent(),
like image 118
user113716 Avatar answered Aug 04 '26 14:08

user113716


I'm not entirely clear on your question, but I might do something like this:

window.someControl = {
    contextElement: $('selector0'),
    selectors: ['selector1', 'selector2']
}

someControl.contextElement.delegate(someControl.selectors.join(','), 'click', function(){ 
    // …
});

Note that the syntax for creating objects JavaScript looks like this:

{
    key: value
}

Not like this:

{
    key = value
}
like image 26
s4y Avatar answered Aug 04 '26 13:08

s4y



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!