« Return to Thread: Change href of external links

Re: Change href of external links

by dave.methvin :: Rate this Message:

Reply to Author | View in Thread

Uh oh, I know what it is. It's a bug in pushStack.
 
If the last arg to pushStack is a function, it does .each(fn) with the filtered set but returns the original set. If there are two trailing function args, the first is treated as above. However, if the filtered set returned nothing (and thus fn was never called) it does .each(fn2) with the original set. Kind of like an if-then-else. It's never been documented but I think it will be eventually.
 
I think this should fix it:
 
 pushStack: function(a,args) {
  var fn = args && args.length > 1 && args[args.length-1];
  var fn2 = args && args.length > 2 && args[args.length-2];
 

From: discuss-bounces@... [mailto:discuss-bounces@...] On Behalf Of Jonathan Sharp
Sent: Thursday, December 14, 2006 2:31 PM
To: jQuery Discussion.
Subject: Re: [jQuery] Change href of external links

On 12/14/06, Yehuda Katz <wycats@...> wrote:
> If that was the case, jQuery("#main a").filter(function() { return false; }) would return nothing. But it doesn't. It returns the original group of elements. At least for me.

Hm... I also tested this and filter didn't prune the list with my function returning false.

Here's the filter function out of 1.0.3 which checks if t is a function and pushes the result of jQuery.grep(this, t) onto the stack.

filter: function(t) {
        return this.pushStack(
            *SNIP*

            typeof t == "function" &&
            jQuery.grep( this, t ) ||

            jQuery.filter(t,this).r, arguments );
    },

Now in the grep function it operates on the list of elements in elms. It calls the function we defined (fn) and if fn returns false it shouldn't add them to the result array.

grep: function(elems, fn, inv) {
        *SNIP*
        var result = [];

        // Go through the array, only saving the items
        // that pass the validator function
        for ( var i = 0; i < elems.length; i++ )
            if ( !inv && fn(elems[i],i) || inv && !fn(elems[i],i) )
                result.push( elems[i] );

        return result;
    },

Am I missing something here?

Cheers,
-js


_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

 « Return to Thread: Change href of external links

LightInTheBox - Buy quality products at wholesale price