开发者

JQuery Plugin Structure. Methods with options, Methods, and Options

I've been attempting to grasp my mind around a good way to structure a plugin so it can accept method calls with options, just method calls, options on init, and init without options.

So far here is what i have.

(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");
});

however with this I receive

test: test args passed

and

args: undefined

Any help?


(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");
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜