如何模拟Jquery UI API?

Joh*_*lum 5 javascript jquery jquery-ui jquery-plugins

我以前写过基本的jQuery插件,但是我正在努力解决一些更复杂的问题.我想模仿jQuery UI的API,它的工作原理如下:

$('#mydiv').sortable({name: 'value'}); // constructor, options
$('#mydiv').sortable("serialize"); // call a method, with existing options
$('#mydiv').sortable('option', 'axis', 'x'); // get an existing option
Run Code Online (Sandbox Code Playgroud)

我尝试过以下方法:

(function($){
    $.fn.myPlugin = function(cmd){
        var config = {
            default: 'defaultVal'
        };

        if(typeof cmd === 'object'){
            $.extend(config, cmd);
        }

        function _foo(){
            console.log(config.default);
        }

        if(cmd==='foo'){
            return _foo();
        }

        this.each(function(){
            // do default stuff
        });
    }
})(jQuery);

$('#myElement').myPlugin({default: 'newVal'});
$('#myElement').myPlugin('foo');
Run Code Online (Sandbox Code Playgroud)

我想在这里看到的是'newval'被记录,但我看到的是'defaultVal'; 每当我在元素上调用.myPlugin()时,就会调用插件并从头开始.

我也尝试过使用_foo.call(this)和其他一些变体.没有快乐.

在某种程度上,我理解为什么会发生这种情况,但我知道必须有可能以与jQuery UI相同的方式来实现.我只是看不出来怎么样!

(我很欣赏jQuery UI使用小部件工厂来处理所有这些,但我不想让它成为插件的要求.)

Dre*_*lls 4

也许你想要的是这个...

(function($){

    var config = {
        default: 'defaultVal'
    };

    $.fn.myPlugin = function(cmd){

        if(typeof cmd === 'object'){
            $.extend(config, cmd);
        }

        function _foo(){
            console.log(config.default);
        }

        if(cmd==='foo'){
            return _foo();
        }

        this.each(function(){
            // do default stuff
        });
    }
})(jQuery);

$('#myElement').myPlugin({default: 'newVal'});
$('#myElement').myPlugin('foo');
Run Code Online (Sandbox Code Playgroud)

config变量移到函数之外myPlugin。此更改将导致config仅初始化一次:创建插件函数时。

  • 嘎!我还没打字完你就发帖了。 (2认同)