如何扩展jQuery插件?

3
我是为jQuery编写插件的。我遇到了扩展插件的问题。例如,我编写了以下插件:http://docs.jquery.com/Plugins/Authoring
请查看以下示例代码:
(function($){
    var i18n    = {};
    var methods = {};
    $.fn.myPlugin = function(options){
        //...
   };
})(jQuery);

我该如何扩展属性 i18n

我想支持存储在单独文件中的国际化插件设置。我应该怎么做?

4个回答

2

例如:

// plugin definition
$.fn.hilight = function(options) {
  // Extend our default options with those provided.
  // Note that the first arg to extend is an empty object -
  // this is to keep from overriding our "defaults" object.
  var opts = $.extend({}, $.fn.hilight.defaults, options);
  // Our plugin implementation code goes here.
};
// plugin defaults - added as a property on our plugin function
$.fn.hilight.defaults = {
  foreground: 'red',
  background: 'yellow'
};

从这里开始 http://www.learningjquery.com/2007/10/a-plugin-development-pattern

这是一个非常好的教程,适合初学者入门。


1

jQuery插件通常会像这样扩展选项:

var i18nOpts = $.extend({}, i18n, options.i18n);

文档:http://docs.jquery.com/Plugins/Authoring#Defaults_and_Options

这发生在插件本身内部。

(function($){
    var i18n    = {};
    var methods = {};
    $.fn.myPlugin = function(options){
        var i18nOpts = $.extend({}, i18n, options.i18n);
   };
})(jQuery);

i18n仅存在于该函数内部,要扩展它,现在可以向插件传递选项。

$('#myDiv').myPlugin({
    i18n: {
        option1: "value",
        option2: "Value2"
    }
});

@IgorTimoshenko:i18n 变量只能从其所在的匿名函数内部访问。 - gen_Eric
@IgorTimoshenko:你想做什么?你不能从该函数外部访问i18n。当你调用插件时,你需要传递选项,并像我展示的那样使用$.extend来扩展它(从插件内部)。 - gen_Eric
@IgorTimoshenko:看一下coder的回答。你可以有一个单独的文件来为$.fn.myPlugin.defaults分配值。 - gen_Eric
我应该像 $.myPlugin.i18n 一样存储国际化设置吗? - Igor Timoshenko
如果您在插件之后加载设置文件,则可以从设置文件中执行$.fn.myPlugin.i18n = {}。然后在插件中,您可以读取$.fn.myPlugin.i18n - gen_Eric
显示剩余2条评论

1
以下是我个人使用的便捷模板。
(function($){

var MyClass = function (element, options){

   this.options = $.extend({}, options);

   this.someFunction = function (){...}  //Public members

   var otherFunction = function(){...}   //Private members

   $(element).data('pluginInstance', this);   

}


$.fn.myPlugin = function(options){

    var myClassInstace = new MyClass(this, options);

    //Do other things with the object.
}

})(jQuery);

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接