views:

157

answers:

1

I'm trying to build a simple jquery plugin that can take selectors as parameters. All of the examples I find expect more raw 'properties' (width, color, etc) than actual selectors. Are there any good ways to do this?

I found this article : http://stackoverflow.com/questions/541362/passing-jquery-selector-to-sub-function-within-a-plugin

But I'm still relatively confused.

The goal is kind of like this ...

        (function ($) {
            $.fn.demonstration = function (options) {

                var defaults = {
                    $selector: null
                };
                var options = $.extend(defaults, options);

                return this.each(function () {
                    alert($selector.attr('id'));
                });
            };
        })(jQuery);

        $('body').demonstration({ $selector: $('#canvas') });
+2  A: 

A selector is nothing more than a string. As long as you wrap any access to a jQuery() ($) call, people can pass in pretty much anything (a selector string, a jQuery object, a DOM element, etc.)

Edit: Saw you added code, in this case you should access it by $(options.$selector).attr('id').

Out of curiosity, why the $ before selector?

Matti Virkkunen
Because that's what I see everyone else using. No idea why they use it. I'm javascript retarded and still learning it.
Stacey
Matt
Okay, I have a question. Is it possible to pass two values at once? Such that $('body').demonstration( 'selector', 'something else' ). My goal is to pass more than just one selector, however. Any ideas?
Stacey
Since jQuery works well with lists (make sure your plugin does too, the .each is a good sign), just have people pass in one object (which you then access with $()). If people want to pass in many things, they can just pass a jQuery object with whatever elements they want.
Matti Virkkunen
My basic goal is a small event pool, where objects with non-form events can be submitted to the pool - and then when I need to trigger the event, I trigger it on the pool and it raises it on everything that has been added to the pool. Am I at least taking the semi-right approach to that, or am I way out in left field?
Stacey
It sounds like you're trying to create a robust selection system, which jQuery already has. You would simply use their selectors to weed out which items you want to select. Check it out: http://api.jquery.com/category/selectors/
dclowd9901
Well, I'm trying to write something that will let me call one place to trigger a named event on everything that has subscribed to the event.
Stacey