Reputation: 22007
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.
Upvotes: 5
Views: 105
Reputation: 1226
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/
Upvotes: 0
Reputation: 4428
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?
Upvotes: 0
Reputation: 3097
$.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.
Upvotes: 2