Access to selector from sub function?
Let's say I've created this plugin:
$.fn.my_namespace = function() {}开发者_JAVA百科
with level 1 sub functions:
$.fn.my_namespace.category_func = function() {}
and level 2 sub functions (actual application):
$.fn.my_namespace.category_func.app_func() {
alert(this);
alert(this.selector);
}
Execution:
$('div').my_namespace.category_func.app_func();
how can I now in my app_func retrieve the actual selector? In this case, 'this' seems to be the parent function (category_func) and not the jQuery object (selector).
How come? And how do I access the selector from app_func() ?
jQuerys .fn
namespace is intended to hold functions
which return a jQuery object
/ array of objects
.
You can't just throw a new object in there and expect everything to work just like that.
I swear I've answered this before, but I can't seem to find it. this
always refers to the object you are calling the method on. In this case you are using category_func
as that object, and calling app_func()
.
The pattern that jQuery UI uses is one possible way to work around this issue. They allow you to call methods on a UI object by doing something like $elem.draggable('destroy');
Imagine for a moment:
$.fn.my_namespace = function(submethod, method) {
var args = [].slice.call(arguments, 1);
var func = $.fn.my_namespace[submethod];
if (func && method) {
if ($.isFunction(func[method])) {
args.shift(); // remove the method
func = func[method];
}
}
if ($.isFunction(func)) {
// using .apply() allows us to pass `this` along to our "method functions"
return func.apply(this, args);
} else {
// didn't find the method, return... or do something else...
console.log('my_namespace', this, arguments);
return this; // jQuery chaining default
}
}
$.fn.my_namespace.category_func = function() {
console.log('category_func', this, arguments);
return this;
}
$.fn.my_namespace.category_func.method_func = function() {
console.log('method_func', this, arguments);
return this;
}
$("body").my_namespace('category_func', 'method_func', 10);
//method_func jQuery(body) [10]
$("body").my_namespace('category_func', 10);
//category_func jQuery(body) [10]
$("body").my_namespace(10, 'slow');
//my_namespace jQuery(body) [10, "slow"]
精彩评论