2011-04-13 271 views
5

我定义上http://docs.jquery.com/Plugins/AuthoringjQuery插件调用内部其他公共职能的公共功能

(function($){ 

    var methods = { 
    init : function(options) { }, 
    show : function(options) { }, 
    hide : function() { }, 
    update : function(content) { 
     // How to call the show method inside the update method 
     // I tried these but it does not work 
     // Error: not a function 
     this.show(); 
     var arguments = { param: param }; 
     var method = 'show'; 
     // Error: options is undefined 
     methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1)); 
    } 
    }; 

    $.fn.tooltip = function(method) { 

    // Method calling logic 
    if (methods[method]) { 
     return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1)); 
    } else if (typeof method === 'object' || ! method) { 
     return methods.init.apply(this, arguments); 
    } else { 
     $.error('Method ' + method + ' does not exist on jQuery.tooltip'); 
    }  

    }; 

})(jQuery); 

我的插件基地如何调用Update方法里面的表演方法?

EDIT

show方法引用this。使用methods.show(options)methods['show'](Array.prototype.slice.call(arguments, 1));可以调用show方法,但由于我得到this.find(...) is not a function错误,因此对this的引用似乎是错误的。

show方法:

show: function(options) { 
    alert("Options: " + options); 
    alert("Options Type: " + options.interactionType); 
    var typeCapitalized = capitalize(options.interactionType); 
    var errorList = this.find('#report' + typeCapitalized); 
    errorList.html(''); 
}, 

回答

14
var methods = { 
    init : function(options) { }, 
    show : function(options) { }, 
    hide : function() { }, 
    update : function(options) { 

    methods.show.call(this, options); 

    } 
}; 
+0

'methods.show()'的作品,但不是'$(本).show()' – Sydney 2011-04-14 13:58:43

+0

好吧,我不太确定'$(this).show();'。 – 2011-04-14 13:59:50

+0

我编辑了这个问题,因为现在我在'show'方法里面有一个问题,因为对'this'的引用。 – Sydney 2011-04-14 14:21:17

1

您使用的是.apply什么的扔在这里的一切了。你故意更改什么this的意思,这是什么使this.show()无法正常工作。如果你想this继续成为methods(这是有道理的),你可以简单地做:

return methods[ method ](Array.prototype.slice.call(arguments, 1));