2010-08-24 92 views
0

比方说,我创建了这个插件:从子函数访问选择器?


$.fn.my_namespace = function() {} 

与一级子功能:

$.fn.my_namespace.category_func = function() {} 

和二级子功能(实际应用):

$.fn.my_namespace.category_func.app_func() { 
    alert(this); 
    alert(this.selector); 
} 

执行:

$('div').my_namespace.category_func.app_func(); 

我该如何在我的app_func中检索实际的选择器?在这种情况下,'this'似乎是父函数(category_func),而不是jQuery对象(选择器)。

怎么回事?我如何从app_func()访问选择器?

回答

0

jQuerys .fn命名空间旨在容纳functions,它返回jQuery object/array of objects

你不能只是抛出一个新的对象,并期望一切工作就像那样。

0

我发誓我已经回答过这个,但我似乎无法找到它。 this总是指您正在调用方法的对象。在这种情况下,您使用category_func作为该对象,并调用app_func()

jQuery UI使用的模式是解决此问题的一种可能方式。它们允许你做类似$elem.draggable('destroy');

想象一下调用UI对象的方法:

$.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"]