Ali Habibzadeh
Ali Habibzadeh

Reputation: 11558

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

Upvotes: 3

Views: 500

Answers (2)

s4y
s4y

Reputation: 51685

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
}

Upvotes: 1

user113716
user113716

Reputation: 322492

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(),

Upvotes: 2

Related Questions