jQuery Plugin Namespacing Functions

后端 未结 4 851
-上瘾入骨i
-上瘾入骨i 2021-02-04 15:20

I\'m creating a jQuery plugin that that is rather large in scope. In fact, the plugin technically consists of a few plugins that all work together.

(function($){         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-04 16:19

    I know this has already been answered but I have created a plugin that does exactly what you want:

    http://code.google.com/p/jquery-plugin-dev/source/browse/trunk/jquery.plugin.js

    I've included a small example below, but check out this jQuery Dev Group post for a more in-depth example: http://groups.google.com/group/jquery-dev/browse_thread/thread/664cb89b43ccb92c/72cf730045d4333a?hl=en&q=structure+plugin+authoring#72cf730045d4333a

    It allows you to create an object with as many methods as you want:

    var _myPlugin = function() {
        // return the plugin namespace
        return this;
    }
    
    _myPlugin.prototype.alertHtml = function() {
        // use this the same way you would with jQuery
        alert($(this).html());
    }
    
    $.fn.plugin.add('myPlugin', _myPlugin);
    

    now you can go:

    $(someElement).myPlugin().alertHtml();
    

    There are, of course, many, many other possibilities with this as explained in the dev group post.

提交回复
热议问题