Use jQuery's end() in my plugins

104 views Asked by At

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.

3

There are 3 answers

3
Bruno Silva On BEST ANSWER
$.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.

1
Leo On

To me it looks like the way you are writing the plugin disturbs the logic of jQuery since you are returning something that jQuery might not expect. That is just a guess though, since I do not know jQuery well at all.

Maybe you can do what you want in .doSomething() instead?

1
whitneyit On

If you look at the data on $( '#a' ) it's just a string saying '#c' not an actual jQuery Object. I updated the code for you http://jsfiddle.net/89gkD/3/