使用函数扩展jquery插件对象

时间:2010-08-07 13:26:39

标签: javascript jquery plugins function

我正在尝试编写一个新的jQuery插件。

base(这不是我的插件,只是为了更好地理解):

(function($) {
    $.fn.mySuperCoolPlugin = function(options) {

        // Build main options before element iteration
        var opts = $.extend({}, $.fn.mySuperCoolPlugin.defaults, options);

        var editText= 'pre ' + opts.text + ' post';


        return this.each(function() {
            $(this).html(editText);
        });

    }

    // Default settings
    $.fn.mySuperCoolPlugin.defaults = {
        text: 'hi'
    }

})(jQuery);

现在运行我的插件后,我想在其上做一些额外的功能。

var plug = $('.text').mySuperCoolPlugin({text: 'running it'});
plug.runAnotherFunction('blabla');
// this for example should set the html to "pre running it post blabla"
例如,

plug.runAnotherFunction现在应扩展我以前的文字并添加我输入的文字。

你知道我的意思吗?如何在我的插件中添加额外的功能?我只看到你用一些选项运行一次的插件。

3 个答案:

答案 0 :(得分:1)

只需在插件下添加该功能:

   (function($) {
        $.fn.mySuperCoolPlugin = function(options) {

            // Build main options before element iteration
            var opts = $.extend({}, $.fn.mySuperCoolPlugin.defaults, options);

            var editText= 'pre ' + opts.text + ' post';


            return this.each(function() {
                $(this).html(editText);
            });

        }

        // Default settings
        $.fn.mySuperCoolPlugin.defaults = {
            text: 'hi'
        }

        $.fn.mySuperCoolPlugin.runAnotherFunction = function(){
            return "this is another function";
        }

    })(jQuery);

答案 1 :(得分:0)

你需要创建包装方法。并且有一条重要的规则:它必须返回包裹的集合。因此,您必须返回'this'(指包装的集合)以允许链接(您还需要它)。您可以使用以下模式执行此操作:

(function($){
  $.fn.runAnotherFunction = function() {
    // put your code here
    // but you have to return 'this' to allow the chaining
  }
})(jQuery);

或者,更好的说法(为了迭代内部的所有包装集):

(function($){
  $.fn.runAnotherFunction = function() {
    return this.each(function(){
      // put your code here
    });
  }
})(jQuery);

答案 2 :(得分:0)

在返回this.each函数中向'this'添加方法将不起作用。至少它在adobe air中不起作用。

我试过了:

return this.each(function(){
     this.myActionFunction = function() { /* code here */ };
}

但是代码:

var myPluginObject = $(...).myPlugion({..});
myPluginObject.myActionFunction(); // faild
myPluginObject.first().myActionFunction(); //faild

所以我最终使用了一个对象来封装插件使用的对象。我的对象看起来像这样:

var myPlugin = function(args) {
   return this.init();
}

var myPlugin.prototype = {
    init : function(args) { 
         if(args !== undefinded)                
             this.target = args.target // this is the $(...) object
         this.target.pluginCall(args.pluginArgs); // call the plugin method
         return this;
    },

    myActionMethod : function() {
        var target = this.target;
        // do something with target, which is the actual plugin object returned from the
        // plugin code.
    }
}

var pluginInstance = new myPlugin({
     target : $("#myOjbect"),
     pluginArgs : {
        /* plugin args here */
     }
});

pluginInstance.myActionMethod(); // works!