将jquery插件配置存储在数据中是一个好习惯吗?

ins*_*ser 12 javascript jquery plugins

我想用config创建jQuery插件(例如插件myplugin).比调用$(elem).myplugin(config);之后我想从这个插件调用方法,就像$(elem).myplugin().method()已经存储的配置一样.

我的报价是这样的:

(function($) {
    $.fn.myplugin = function(options) { 
        var $this = $(this);

        var getOptions = function() {
            return $this.data('myplugin');
        };

        var initOptions = function(opt) {
            $this.data('myplugin', opt);
        };

        var setOption = function(key, value) {
            $this.data('myplugin')[key] = value;
        }

        var updateBorderWidth = function() {  
            $this.css('border-width', 
                      getOptions().borderWidth * getOptions().coeficient);
        };

        var init = function(opt) {
            initOptions(opt);
            updateBorderWidth();
        }        

        function changeBorder(width) {            
            setOption('borderWidth', width)
            updateBorderWidth();
        }

        if(options) {
            init(options);            
        }        

        return {
            changeBorder : changeBorder
        };
    }        
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

用法:

 $(function() {
     var item1 = $('#test1').myplugin({ coeficient: 1, borderWidth: 1 });
     var item1 = $('#test2').myplugin({ coeficient: 2, borderWidth: 1 });

     $('#btn').click(updateBorder);     
});

function updateBorder() {
    $('#test1').myplugin().changeBorder($('#inpt').val());
    $('#test2').myplugin().changeBorder($('#inpt').val());
}
Run Code Online (Sandbox Code Playgroud)

示例:http://jsfiddle.net/inser/zQumX/4/

我的问题:这样做是一种好习惯吗?

可能是不正确的方法.你能提供更好的解决方案吗

Nol*_*olo 3

编辑:

在搜索jQuery 插件模板上的线程后,我发现了这些样板模板(已更新),它们比我下面提供的模板更通用、更广泛。最终您的选择取决于您的需求。样板模板涵盖的用例比我提供的要多,但每个模板都有自己的优点和注意事项,具体取决于要求。


通常,当将值传递给 jQuery 插件时,它们会返回 jQuery 对象,如下所示:

.wrap(html) // returns a jQuery object
Run Code Online (Sandbox Code Playgroud)

或者当没有传入参数时它们返回一个值

.width() // returns a value

.height() // also returns a value
Run Code Online (Sandbox Code Playgroud)

要阅读您的示例调用约定:

$('#test1').myplugin().changeBorder($('#inpt').val());

对于任何使用 jQuery 的开发人员来说,似乎同时使用了两个单独的插件,第一个.myplugin()插件会返回一个 jQuery 对象,并执行一些默认的 DOM 操作#test1,然后接下来的.changeBorder($('#inpt').val())插件也可能返回一个 jQuery 对象但在你的例子中,整行没有分配给一个变量,所以没有使用任何返回值——它看起来又像一个 DOM 操作。但是您的设计不遵循我所描述的标准调用约定,因此如果任何人不熟悉您的插件,查看您的代码的人可能会对其实际功能感到困惑。


我过去曾考虑过与您所描述的问题和用例类似的问题和用例,并且我喜欢采用一种方便的约定来调用与插件关联的单独函数的想法。选择完全取决于您 - 这是您的插件,您需要根据谁将使用它来决定,但我选择的方式是简单地传递函数的名称及其参数作为单独的.myplugin(name, parameters)或在一个对象中作为.myplugin(object).

我通常这样做:

(function($) {
    $.fn.myplugin = function(fn, o) { // both fn and o are [optional]
        return this.each(function(){ // each() allows you to keep internal data separate for each DOM object that's being manipulated in case the jQuery object (from the original selector that generated this jQuery) is being referenced for later use
            var $this = $(this); // in case $this is referenced in the short cuts
            
            // short cut methods
            if(fn==="method1") {
                if ($this.data("method1"))  // if not initialized method invocation fails
                    $this.data("method1")() // the () invokes the method passing user options
            } else if(fn==="method2") {
                if ($this.data("method2"))
                    $this.data("method2")()
            } else if(fn==="method3") {
                if ($this.data("method3"))
                    $this.data("method3")(o) // passing the user options to the method
            } else if(fn==="destroy") {
                if ($this.data("destroy"))
                    $this.data("destroy")()
            }
            // continue with initial configuration
            
            var _data1,
                _data2,
                _default = { // contains all default parameters for any functions that may be called
                    param1: "value #1",
                    param2: "value #2",
                },
                _options = {
                    param1: (o===undefined) ? _default.param1 : (o.param1===undefined) ? _default.param1 : o.param1,
                    param2: (o===undefined) ? _default.param2 : (o.param2===undefined) ? _default.param2 : o.param2,
                    
                }
                method1 = function(){
                    // do something that requires no parameters
                    return;
                },
                method2 = function(){
                    // do some other thing that requires no parameters
                    return;
                },
                method3 = function(){
                    // does something with param1
                    // _options can be reset from the user options parameter - (o) - from within any of these methods as is done above
                    return;
                },
                initialize = function(){
                    // may or may not use data1, data2, param1 and param2
                    $this
                        .data("method1", method1)
                        .data("method2", method2)
                        .data("method3", method3)
                        .data("destroy", destroy);
                },
                destroy = function(){
                    // be sure to unbind any events that were bound in initialize(), then:
                    $this
                        .removeData("method1", method1)
                        .removeData("method2", method2)
                        .removeData("method3", method3)
                        .removeData("destroy", destroy);
                }
            initialize();
        }) // end of each()
    } // end of function        
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

以及用法:

var $test = $('#test').myplugin(false, {param1: 'first value', param2: 'second value'}); // initializes the object
$test.myplugin('method3', {param1: 'some new value', param2: 'second new value'}); // change some values (method invocation with params)
Run Code Online (Sandbox Code Playgroud)

或者你可以直接说:

$('#test').myplugin(); // assume defaults and initialize the selector
Run Code Online (Sandbox Code Playgroud)