views:

38

answers:

2

I have encountered code that leverages jQuery, similar to the following.

NAMESPACE = {
    propertyA : $("#selector-a"),
    propertyB : $("#selector-b")
}

$(NAMESPACE.propertyA).click(function(){
    // ...
});

This seems to work, even though the syntax for attaching the click handler should be.

NAMESPACE.propertyA.click(function(){
    // ...
});

Does jQuery have the built in ability to resolve the following, despite the incorrect syntax?

$($("#my-selector")).click ... etc.
+1  A: 

Yes, it will handle this if necessary. You really ought not use this syntax though if it's within your control. I tested against the following and got the same results with both:

$($("li")).click(function(e){
  alert(e.target);
});

//--

$("li").click(function(e){
  alert(e.target);
});
Jonathan Sampson
Use of this syntax was not my decision, and I understand that it is not desirable.
jerome
@jerome: No blood, no foul :) I understand having to work with other people's finicky code.
Jonathan Sampson
+3  A: 

Yes. jQuery allows as arguments to the $:

  • A CSS selector
  • A DOM element
  • An array of DOM elements
  • A jQuery object
  • A function (which will be called as part of $.ready())

All of these are valid syntax as far as jQuery is concerned, though performance may suffer in some of these cases.

Since your NAMESPACE.properties are jQuery elements, this will work.

Dan Herbert