2011-04-13 270 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));