0

I'm writing a jQuery plugin called "myplugin" with plugin method "getSomeWhat". This methods may return a collection of somewhat, e.g. attr('id') of element(s) in ".someclass". I'd like to maintain the chainability, but I can't find from the Internet.

Please kindly advise how to achieve.

$(".someclass").myplugin('getSomeWhat').each(function() {
    //some stuff for each somewhat
});

Thanks!

William Choi

1 Answer 1

2

You can't return a non jQuery object and retain chainability. Simply because the chainability is dependent on the jQuery object. It's of course entirely possible to return a jQuery object and allow stuff to chain to that, but that would kinda defeat the purpose of the lookup method.

If you're looking to iterate over the returned set you might accomplish it like this:

var data = $(".someclass").myplugin('getSomeWhat');
$.each(data, function(i, v) {
    //i is index, v is value (if using object props, i is the propName
});

This makes you of the jQuery generic iterator. It can seamlessly iterate over array as well as objects.

Sign up to request clarification or add additional context in comments.

3 Comments

Can't I wrap collection into an jQuery object?
This really depends on the usecase, what is it exactly you're trying to accomplish? You want to iterate over the collection returned by the plugin?
Updated my answer to provide a solution for iteration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.