如何调用插件方法

时间:2014-02-07 06:09:30

标签: jquery

这是我的插件代码

(function( $ ) {

    $.fn.myGrid = function(options) {

        var _myGrid = this;
        var _$myElement;
        var setOutTimer;
        var settings = $.extend({
            url: null,
            dataType: "json",
            colNames: []
        }, options );

        this.initiateGRID = function(that) {
            _$myElement = $(that);            
        }

        this.showInlineSuccess = function(msg){
            //Some Code
        }

        return this.each(function() {        
            _myGrid.initiateGRID(this);
        });

    };

}( jQuery ));

加载插件后,我想从外部调用方法showInlineSuccess $.myGrid.showInlineSuccess('Hello');

如何实现这一目标?

3 个答案:

答案 0 :(得分:1)

你应该设计它,

   (function( $ ) {

      function Grid(options) {

         this._myGrid = null,
         this._$myElement = null,
         // other properties of grid

      }

      // add methods to Grid class
      Grid.prototype = {

        initiateGRID : function(that) {
           var grid = this;     
           grid._$myElement = $(that);

        },

        howInlineSuccess : function(msg){
                //Some Code

        }
      }

      $.fn.myGrid = function(options) {

        var settings = $.extend({
                url: null,
                dataType: "json",
                colNames: []
            }, options );

        return new Grid(settings)

      }  

    }( jQuery ));

现在你可以称之为,

var grid = $('some selector').myGrid()
grid.showInlineSuccess('Hello')

如果你想把它称为

var grid = $.myGrid()
grid.showInlineSuccess('Hello')

然后将插件更改为

$.myGrid = function(options) { // code

答案 1 :(得分:1)

这可以满足您的需求,但不要相信这是最好的方法。

$.fn.myGrid().showInlineSuccess('asdfasdfasdf');

注意myGrid之后的()

答案 2 :(得分:0)

使用此:

$.fn.myGrid.showInlineSuccess('Hello');

而不是:

$.myGrid.showInlineSuccess('Hello');


您缺少fn