Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery's end() in my plugins

How can I copy the stack of a jQuery object to another jQuery object, so I can use end in my plugins even when returning totally unrelated objects? Example:

$(myselector)
    .next()             // Destructive operation
        .doSomething()
    .end()              // Goes back to "myselector"
    .doSomethingElse(); // Works fine!

$.fn.myPlugin = function() {
    return $(unrelated); // No stack, can't call "end" on it
};

$(myselector)
    .myPlugin()         // Destructive operation
        .doSomething()
    .end()              // Goes back to nowhere, since the stack is empty
    .doSomethingElse(); // Doesn't work

I'd like to modify the $(unrelated) object to include this's stack, so the second example would work. Here's a complete example in jsFiddle.

like image 971
mgibsonbr Avatar asked Nov 05 '22 06:11

mgibsonbr


1 Answers

$.fn.myPlugin = function(related) {
    if ( related == "getRelated" )
        return this.pushStack($(this.data("related")).get()); // Want to preserve stack
    return this.data("related",related);
};

You need to push the element to the stack so that end() gets back to it.

like image 193
Bruno Silva Avatar answered Nov 07 '22 23:11

Bruno Silva