Структура плагинов JQuery.Методы с опциями, Методы и опции - PullRequest
4 голосов
/ 24 августа 2011

Я пытался осмыслить хороший способ структурирования плагина, чтобы он мог принимать вызовы методов с параметрами, только вызовы методов, параметры init и init без параметров.

Пока вот что у меня есть.

(function($) {
    var settings = {};
    var defaults = {
        args : "default args"
    };
    var methods = {
        init : function(options) {
            if(options) {
                settings = $.extend({},defaults,options);
            }
        },
        test : function(arg) {
            alert("test: " + arg.args);
            alert("args: " + settings.args);
        }
    };
    $.fn.dataTable = function(method) {
        var args = arguments;
        var $this = this;
        return this.each(function() {
            if ( methods[method] ) {
                return methods[method].apply( $this, Array.prototype.slice.call( args, 1 ));
            } else if ( typeof method === 'object' || ! method ) {
                return methods.init.apply( $this, args );
            } else {
                $.error( 'Method ' +  method + ' does not exist on jQuery.plugin' );
            }  
        });
    };

})(jQuery);


$(document).ready(function(){
    $(".tbl").dataTable();
    //$(".tbl").dataTable({ args : "hello world" });
    $(".tbl").dataTable("test",{args:"test args passed"});
    //$(".tbl").dataTable("test");
});

однако с этим я получаю

test: аргументы теста пройдены

и

args: undefined

Любая помощь?

1 Ответ

3 голосов
/ 24 августа 2011
(function($) {
    var defaults = {
        string1 : "hello ",
        string2 : "world!"
    };
    var methods = {
        init : function(options) {
            if(options) {
                $.extend(defaults,options);
            }
            alert(defaults.string1 + defaults.string2);
        },
        test : function(arg) {
            alert("test: " + arg.args);
            alert("args: " + defaults.string1 + defaults.string2);
        }
    };
    $.fn.dataTable = function(method) {
        var args = arguments;
        var $this = this;
        return this.each(function() {
            if ( methods[method] ) {
                return methods[method].apply( $this, Array.prototype.slice.call( args, 1 ));
            } else if ( typeof method === 'object' || ! method ) {
                return methods.init.apply( $this, Array.prototype.slice.call( args, 0 ) );
            } else {
                $.error( 'Method ' +  method + ' does not exist on jQuery.plugin' );
            }  
        });
    };

})(jQuery);


$(document).ready(function(){
    $(".tbl").dataTable();
    //$(".tbl").dataTable({ string1 : "foo", string2 : "bar" });
    $(".tbl").dataTable("test",{args:"test args passed"});
    //$(".tbl").dataTable("test");
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...