Matthew Layton
Matthew Layton

Reputation: 42340

Passing correct jQuery selector to an object

I am writing a jQuery plugin which, ideally I would like in it's own namespace.

So far, this seems to work (in terms of namespace nesting)

(function($) {
    $.fn.nspace = {
        foo: function() {
            // Does not work becuase $(this) is not the correct selector.
            $(this).show();
        }
    }
})(jQuery);

So given then example above, I might call my function like so:

$("html, body").nspace.foo();

but $(this) is not [html, body]...How can I solve this?

EDIT: To clarify (based on user comments)...

$("html, body").nspace.foo(); should call foo for [html, body] but, $(this) inside nspace resolves to nspace...so it's trying to call nspace.foo();

Upvotes: 2

Views: 100

Answers (3)

Chris Moschini
Chris Moschini

Reputation: 37967

You shouldn't do this, but just because I dislike when someone says "You can't" in programming (often untrue, especially in Javascript) - here's how you could do this:

The jQuery object is constructed each time using its prototype.init function, which is aliased to fn.init, so you could overwrite it with a wrapped function that adds your namespace object in a way that doesn't harm any existing usage or libraries, like so:

(function($) {
    var baseInit = $.fn.init;
    $.fn.init = function(selector, context, rootjQuery) {
        // Instantiate jQuery the way it expects
        var j = new baseInit(selector, context, rootjQuery);

        // Add our extra object/namespace
        // Use j inside to refer to the current jQuery object
        j.nspace = {
            foo: function() {
                j.show();
            }
        };

        // Return it all and other libraries are none the wiser
        return j;
    }
})(jQuery);

http://jsfiddle.net/b9chris/7TPZY/

Upvotes: 1

Loamhoof
Loamhoof

Reputation: 8293

You should consider using the classic pattern for a jQuery plugin: define only one method: in your case, nspace. Inside this method, you'll take every case into account. Sounds hard, but it's pretty easy once you've looked into that. (By the way you definitely have to look at that when writing a jQuery plugin)

Upvotes: 1

Guffa
Guffa

Reputation: 700680

You can't add an object as a plugin and still get the jQuery object that was used to get the object. You simply have no reference to that jQuery object when you call a method in your object.

Put the function directly as the plugin:

(function($) {
  $.fn.nspace = function() {
    this.show();
  };
})(jQuery);

Usage:

$("html, body").nspace();

(Note that the object is the jQuery instance, not a selector or an element, so you don't need to use $(this)).

Upvotes: 0

Related Questions