jQuery: How to make function in an object public?
I use a pagination plugin and I'd like to make one of it's functions public, so I can call it from "outside". I can not call it di开发者_如何转开发rectly, using pageSelected($(obj))
.
Is there an easy way to make it visible so I can call it?
Jerry
window
is the global object in JavaScript, so do window.myfunc = myfunc
and myfunc
will be available globally.
Have a look at line 818 of the jQuery core source to see an example of this in action:
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
You could also use a more Object-Oriented way to write plugins.
Hector Virgen posted a great approach on his blog:
http://www.virgentech.com/blog/2009/10/building-object-oriented-jquery-plugin.html
Plugin code:
(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);
Calling the plugin:
$('#test').myplugin();
var myplugin = $('#test').data('myplugin');
myplugin.publicMethod(); // prints "publicMethod() called!" to console
精彩评论