jQuery插件的优化

时间:2019-03-19 23:47:56

标签: jquery

我没问题,但是我想提出一些建议: 我已经阅读了一些有关做一些jquery插件的帮助,而我只是做了我的第一个。 它有助于生成动态数据表:使用一些JSON数据自动填充表格,并创建一些触发器以添加或修改某些行。 我有一个表单,它将添加一些行,并且单击表中的一行将更改该行以显示一些输入和一个保存按钮。 我将通过一行呼叫我的插件:

$("table#listClient").dataTableAuto();

一切正常!但是由于有我的第一个JQuery插件,我想提出一些建议来对其进行优化,并使其尽可能干净...有更好的方法吗?

是这里:

(function($) {
    var PLUGIN_NS = 'dataTableAuto';

    var Plugin = function ( target, options ) { 
        this.$T = $(target); 
        this._init( target, options ); 
        return this; 

        /** the options */
        this.options= $.extend(
            true, {
                DEBUG: false
            },
            options
        );

    }
    /* Init */
    Plugin.prototype._init = function ( target, options ) { 
        /* all default values are generated with the table id, but can be changed if needed */
        var field = $(target).attr("id").split("_")[1];
        defaultAutoOptions = {
            formClassName:  "form_" + field,
            jsonFile:   "/json/json_" + field + ".json",
            submitEvtFct: this._submitEvtFct,
            clickEvtFct: this._clickEvtFct
        }
    this.options = $.extend(defaultAutoOptions, Plugin.defaults, options);
    this.dataTableAuto = this._dataTableAuto(target);
    /* Add some events, which can be change if needed */
    this.options.clickEvtFct(this);
    this.options.submitEvtFct(this);

    return this;
};

/* Default val */
Plugin.defaults = {
    events: function(_, callback){ callback([]) }
};

/* Init the datatable */
Plugin.prototype._dataTableAuto = function ( target, options ) { 
    var _this = this;
    /* Get some data used to init the datatable */
    var infosTable = this._getInfosColumn(target); 
    return tableDT = $(this.$T).DataTable({
        "ajax": {
            'type': 'GET',
            'url': this.options.jsonFile,
            'data':  function ( d ) {
            }
        },
        destroy: true,
        info: false,
        rowId: "lineID",
        'columnDefs': infosTable.listColumnDef,
        "columns": infosTable.listColumn,
        'paging' : false,
        "searching": false,
        "initComplete": function( settings, json ) {
            if (typeof json['eval']!='undefined'){
                eval(json['eval']);
            }
        },
        createdRow: function( row, data, dataIndex ) {
            _this._setClickableRow(target, row);
        }
    });
}

/* get column data used for datatable */
Plugin.prototype._getInfosColumn = function ( target) {
    listColumn = [];
    listColumnDef = [];
    attr = $(" > thead > tr th:first-child", $(target[0])).attr("id");
    if (typeof attr === typeof undefined || attr === false) {
        listColumn.push({ "data": "control" });
        listColumnDef.push({ className: 'control', targets: 0 });
    }
    $(" > thead > tr th", $(target[0])).each(function(index) {
        if ($(this).attr("id") != undefined) {
            listColumnDef.push({ responsivePriority: $(this).attr("id") == "col_buttons" ? 1 : index, targets: index});
            if ($(this).hasClass("isDate"))
                listColumn.push(
                    { "data": $(this).attr("id").split("_")[1],
                        render: function ( data, type, row ) {
                           return (data.split("-").length == 3 ? moment(data).format("DD/MM/YYYY") : data);
                        } 
                    }
                )
            else
                listColumn.push({ "data": $(this).attr("id").split("_")[1] })
        }
    })
    return {listColumnDef: listColumnDef, listColumn: listColumn};
}

/* Add a class on cell which can be clicked (depend of the head table line) */
Plugin.prototype._setClickableRow = function (target, row) {
    $(" > thead > tr th", $(target[0])).each(function(index) {
        if ($(this).hasClass("clickable")) {
            $("td:eq(" + index + ")", row).addClass('clickable');
        }
        if ($(this).attr("id") != undefined)
            $("td:eq(" + index + ")", row).addClass($(this).attr("id").split("_")[1]);
    })
}


/* trigger onclick on cells */
Plugin.prototype._clickEvtFct = function ( target, options) {
    $(target.$T).on("click", "tr td.clickable", function() {
        var theRowObject = target.dataTableAuto.row($(this).closest('tr'));
        $.getJSON( target.options.jsonFile, {
            command: "modLigne", 
            lineID: $(this).closest("tr").attr("id").split("_")[1]
        })
        .done(function( data ) {
            data = data.data[0];
            target.dataTableAuto.row(theRowObject).data(data).draw();
            $("tr#" + data.lineID + " td.clickable").addClass("pausedClick").removeClass("clickable");
        });
    })
}

/* trigger send form to add or update line */
Plugin.prototype._submitEvtFct = function ( target) {
    $("body").on("submit",  "form." + target.options.formClassName, function(e) {
        e.preventDefault();
        $.getJSON( target.options.jsonFile, $(this).serialize() + "&command=saveData&lineID=" + ($(this).closest("tr").length > 0 ? $(this).closest("tr").attr("id").split("_")[1] : 0))
        .done(function( datas ) {
            data = datas.data[0];
            var _tr = $("tr#" + data.lineID);
            if (_tr.length > 0) {
                target.dataTableAuto.row($("tr#" + data.lineID).index()).data(data).draw();
                $("tr#" + data.lineID + " td.pausedClick").addClass("clickable").removeClass("pausedClick");
            }
            else {
                target.dataTableAuto.row.add( data ).node().id = data.lineID;
                target.dataTableAuto.draw();
            }
            if(typeof datas['eval']!='undefined')eval(datas['eval']);
        });
    })  
}

/* Remove a line of datatable (called by the ajax call, when a line is deleted) */
Plugin.prototype.removeLine = function ( target, options) {
    this.dataTableAuto.row('#' + options[0]).remove().draw(); 
}

Plugin.prototype.DWARN = function () {
    this.DEBUG && console.warn( arguments );    
}


$.fn[ PLUGIN_NS ] = function( methodOrOptions ) {
    if (!$(this).length) {
        return $(this);
    }
    var instance = $(this).data(PLUGIN_NS);

    if ( instance 
            && methodOrOptions.indexOf('_') != 0 
            && instance[ methodOrOptions ] 
            && typeof( instance[ methodOrOptions ] ) == 'function' ) {

        return instance[ methodOrOptions ](this,  Array.prototype.slice.call( arguments, 1 ) ); 


    } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {

        instance = new Plugin( $(this), methodOrOptions ); 
        $(this).data( PLUGIN_NS, instance );
        return $(this);

    // CASE: method called before init
    } else if ( !instance ) {
        $.error( 'Plugin must be initialised before using method: ' + methodOrOptions );

    // CASE: invalid method
    } else if ( methodOrOptions.indexOf('_') == 0 ) {
        $.error( 'Method ' +  methodOrOptions + ' is private!' );
    } else {
        $.error( 'Method ' +  methodOrOptions + ' does not exist.' );
    }
};
})(jQuery);

谢谢, 马修(Matthieu)

0 个答案:

没有答案