jQuery:如何在对象中公开函数?

时间:2010-08-21 11:51:02

标签: javascript jquery

我使用分页插件,我想将其中一个功能公开,所以我可以从“外部”调用它。我无法使用pageSelected($(obj))直接调用它。

有没有一种简单的方法让它可见,所以我可以打电话给它?

杰里

2 个答案:

答案 0 :(得分:1)

window是JavaScript中的全局对象,因此全局可以使用window.myfunc = myfuncmyfunc

请查看line 818 of the jQuery core source以查看此操作的示例:

// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;

答案 1 :(得分:0)

您还可以使用更加面向对象的方式编写插件。

Hector Virgen在他的博客上发布了一个很好的方法:

http://www.virgentech.com/blog/2009/10/building-object-oriented-jquery-plugin.html

插件代码:

(function($){

   var MyPlugin = function(element, options)
   {
       var elem = $(element);
       var obj = this;
       var settings = $.extend({
           param: 'defaultValue'
       }, options || {});

       // Public method - can be called from client code
       this.publicMethod = function()
       {
           console.log('public method called!');
       };

       // Private method - can only be called from within this object
       var privateMethod = function()
       {
           console.log('private method called!');
       };
   };

   $.fn.myplugin = function(options)
   {
       return this.each(function()
       {
           var element = $(this);

           // Return early if this element already has a plugin instance
           if (element.data('myplugin')) return;

           // pass options to plugin constructor
           var myplugin = new MyPlugin(this, options);

           // Store plugin object in this element's data
           element.data('myplugin', myplugin);
       });
   };

})(jQuery);

调用插件:

$('#test').myplugin();
var myplugin = $('#test').data('myplugin');
myplugin.publicMethod(); // prints "publicMethod() called!" to console