views:

106

answers:

1

I've got a lightbox that uses jQuery's $.ajax to retrieve data.

If i get back no data, then I append a "no data found" message to my list, and a link to reset the search parameters. Basically I'm trying to add a .click() event to a link that I've appended.

The problem is that the function is running immediately, not waiting for a click event.

So when I execute this, the "no data found message" appears briefly and then is replaced by the default results.

function getImages(/* parameters ... */) {
    // other code...
    // if no results:
    $('div#imageLightBox ul.thumbList').append('<li>Sorry, no images found. <a href="#" id="clearSearchLink">Clear search</a>.</li>');
    $('a#clearSearchLink').click(new function() {
        alert("clearSearchLink");
        // code that resets the search parameters ...
        getImages('', '', $('#lightBoxPageSize').val(), 1); // <-- calls the function that contains this code.
    });
};
+3  A: 

click(new function() {

Just ‘function’.

This is a function expression, not a constructor; ‘new Function()’ with the capital F is the explicit constructor version, which you generally don't want to use as it takes and evaluates a string argument every call, which is pretty yucky (and slower).

What is happening is the function expression is creating a new function, then the ‘new’ operator is calling it with a newly-created Object as this (which is what new actually does).

bobince
an anonymous function expression?
Russ Cam
Indeed. Anonymous function expressions are used an awful lot by code in the jQuery style.
bobince
You're right, I don't know why I didn't see that! Long day I guess. Thanks.
Joel Broughton