1. 程式人生 > >jquery開發外掛

jquery開發外掛

1.jQuery.extend(object);為擴充套件jQuery類本身.為類新增新的方法。 
2.jQuery.fn.extend(object);給jQuery物件新增方法。

jQuery便是一個封裝得非常好的'類',比如我們用 語句$("#div1")會生成一個 jQuery類的例項。

jQuery.extend(object);

為jQuery類新增類方法,可以理解為新增靜態方法。

jQuery.extend({
    min: function(a, b) {
        return a < b ? a : b;
    },
    max: function(a, b) {
        return a > b ? a : b;
    }
});
jQuery.min(2, 3); //  2 
jQuery.max(4, 5); //  5

jQuery.fn.extend(object);

就是為jQuery類新增“成員函式”。jQuery類的例項才可以呼叫這個“成員函式”。

 比如我們要開發一個外掛,做一個特殊的編輯框,當它被點選時,便alert 當前編輯框裡的內容。可以這麼做:

$.fn.extend({
    alertWhileClick: function() {
        $(this).click(function() {
            alert($(this).val());
        });
    }
});
//$("#input1")是jQuery的例項,呼叫這個擴充套件方法
$("#input1").alertWhileClick();

jQuery.extend() 的呼叫並不會把方法擴充套件到物件的例項上,引用它的方法也需要通過jQuery類來實現,如jQuery.init()

jQuery.fn.extend()的呼叫把方法擴充套件到了物件的prototype上,所以例項化一個jQuery物件的時候,它就具有了這些方法,在jQuery.JS中到處體現這一點

jQuery.fn = jQuery.prototype

你可以拓展一個物件到jQuery的 prototype裡去,這樣的話就是外掛機制了。

(function($) {
    $.fn.tooltip = function(options) {};
    //等價於 var
    tooltip = {
        function(options) {}
    };
    $.fn.extend(tooltip) = $.prototype.extend(tooltip) = $.fn.tooltip
})(jQuery);

easyui的擴充套件外掛

DataGrid

擴充套件自$.fn.panel.defaults。使用$.fn.datagrid.defaults重寫預設值物件。

方法

外掛

/**
 * 擴充套件帶工具欄的datagrid ,工具欄中的按鈕樣式 用 add, del,save,cancel
 */
(function ($) {
    function init(target) {
        var t = $(target),
            state = $.data(target, 'gridsub'),
            key = state.options.key;
        var editIndex = undefined;
        function endEditing() {
            if (editIndex == undefined) { return true }
            if (t.datagrid('validateRow', editIndex)) {
                var ed = t.datagrid('getEditor', { index: editIndex, field: key });
                t.datagrid('endEdit', editIndex);
                editIndex = undefined;
                return true;
            } else {
                return false;
            }
        }
        t.datagrid({
            title: state.options.title,
            width: state.options.width,
            onClickRow: function (index) {
                if (endEditing()) {
                    t.datagrid('selectRow', index)
                        .datagrid('beginEdit', index);
                    editIndex = index;
                } else {
                    t.datagrid('selectRow', editIndex);
                }
            },
            rownumbers: state.options.rownumbers,
            singleSelect: state.options.singleSelect,
            toolbar: state.options.toolbar,
            pagination: state.options.pagination,
            columns: state.options.columns,
            data: state.options.data,
        });
        $(state.options.toolbar).find("a.add").on("click", function (e) {
            if (endEditing()) {
                t.datagrid('appendRow', {});
                editIndex = t.datagrid('getRows').length - 1;
                t.datagrid('selectRow', editIndex).datagrid('beginEdit', editIndex);
            }
        });
        $(state.options.toolbar).find("a.save").on("click", function (e) {
            if (t.datagrid('validateRow', editIndex)) {
                var ed = t.datagrid('getEditor', { index: editIndex, field: key });
                t.datagrid('endEdit', editIndex);
                t.datagrid('acceptChanges');
                var rows = t.datagrid('getSelected');
                t.datagrid("updateRow", rows);
            }
        });
        $(state.options.toolbar).find("a.del").on("click", function (e) {
            var rows = t.datagrid('getSelected');
            var editIndex = t.datagrid("getRowIndex", rows);
            if (!rows) {
                $Core.UI.message.warning("請選擇一條資料"); return false;
            }
            t.datagrid('cancelEdit', editIndex).datagrid('deleteRow', editIndex);
            editIndex = undefined;
        });
        $(state.options.toolbar).find("a.cancel").on("click", function (e) {
            var row = t.datagrid('getSelected');
            t.datagrid('endEdit', editIndex)
            // if (!state.options.key) {
            //     t.datagrid('deleteRow', editIndex);
            // }
            editIndex = undefined;
        });
    }
    // 外掛的定義     
    $.fn.gridsub = function (options, param) {
        if (typeof options == 'string') {
            var method = $.fn.gridsub.methods[options];
            if (method) {
                return method(this, param);
            }
        }
        return this.each(function () {
            var state = $.data(this, "gridsub");
            if (state) {
                $.extend(state.options, options);
            } else {
                $.data(this, "gridsub",
                    {
                        options: $.extend(true, {}, $.fn.gridsub.defaults, options)
                    });
            }
            init(this);
        });
    };


    $.fn.gridsub.methods = {
        getRows: function (jq) {
            return $(jq[0]).datagrid("getRows");
        },
        load: function (jq, value) {
            return $(jq[0]).datagrid({ data: value });
        }
    };
    // 外掛的defaults     
    $.fn.gridsub.defaults = {
        title: '',
        width: 300,
        //onClickRow: state.onClickRow,
        rownumbers: false,
        singleSelect: false,
        // toolbar: state.toolbar,
        pagination: false,
        columns: [],
        data: [],
    };
    // 閉包結束     
})(jQuery);

外掛使用

                <div class="dg2" style="width:600px;height:300px;margin:10px auto;">
                    <table id="dglist2"></table>
                    <div class="btn_tool2" style="padding:5px;height:auto">
                        <a href="javascript:void(0)"  id="listAdd" class=" easyui-linkbutton" data-options="iconCls:'icon-add',plain:true">新增</a>
                        <a href="javascript:void(0)" class="del easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true">刪除</a>
                        <a href="javascript:void(0)" class="save easyui-linkbutton" data-options="iconCls:'icon-save',plain:true">儲存</a>
                        <a style="display:none;" href="javascript:void(0)" class="cancel easyui-linkbutton"
                           data-options="iconCls:'icon-undo',plain:true">取消</a>
                        <!--<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-search',plain:true" onclick="getChanges()">GetChanges</a>-->
                    </div>
                </div>

$("#dglist2").gridsub({
		    title: '物資',
		    width: 700,
		    key: "id",
		    rownumbers: false,
		    singleSelect: true,
		    toolbar: ".btn_tool2",
		    pagination: false,
		    columns: [[
		        { field: 'materialStoreId', checkbox: true, hidden: true },
		        {
		            field: 'materialName', title: '物資名稱 ', width: '25%', align: 'center', sortable: false
		        },
		        {
		            field: 'materialType', title: '物資型別', width: '25%', align: 'center', formatter: function (value, row, index) {return $Core.DicCache.get('material_type')[value]; }
		        },
		        { field: 'materialInNum', title: '物資數量', width: '25%', align: 'center', sortable: false, editor: { type: 'numberbox', options: { required: false, validType: 'numeric' } } },
		        {
		            field: 'materialModel', title: '規格型號', width: '25%', align: 'center', sortable: false
		        },
		        {
		            field: 'materialProductionDate', title: '生產日期', width: '25%', align: 'center', sortable: false
		        },
		        {
		            field: 'materialManufacturer', title: '生產廠家', width: '25%', align: 'center', sortable: false
		        },
		        {
		            field: 'materialCycle', title: '使用週期', width: '25%', align: 'center', sortable: false
		        },
		        ]],
	
		    //  data: [],
	
	
		});



var rows2 = $("#dglist2").gridsub("getRows");

擴充套件外掛

(function ($) { /*** 統一設定datagrid 的一些預設引數*/
      $.extend($.fn.datagrid.defaults,
        {
            rownumbers: true,
            fit: true,
            pagination: true,
            striped: true,
            method: "post",
            pageSize: 20,
            pageList: [20, 50, 100]
        });
    $.extend($.fn.combobox.defaults,
        {
            editable: false,
            panelHeight: 'auto',
            valueField: 'id',
            textField: 'text',
            labelPosition: 'left',
            method: "get",
            loadFilter: function (data) {
                if ($.util.isArray(data.data))
                    return data.data;
                return data;
            },
            onShowPanel: function () {
                arrowrotate($(this), true);
            },
            onHidePanel: function () {
                arrowrotate($(this), false);
            }
        });   
})(jQuery);

擴充套件自$.fn.combo.defaults。使用$.fn.combobox.defaults重寫預設值物件。

    $("#customerType").combobox({
        url: _self.dicurl+'customerType',
        label: '使用者型別'
    });

擴充套件自$.fn.combo.defaults。使用$.fn.datebox.defaults重寫預設值物件。

    var buttons = $.extend([], $.fn.datebox.defaults.buttons);
    buttons.splice(1,
        1,
        {
            text: '清空',
            handler: function (target) {
                $(target).combo("setValue", "").combo("setText", ""); // 設定空值  
                $(target).combo("hidePanel"); // 點選清空按鈕之後關閉日期選擇面板  
            }
        });
    $.fn.datebox.defaults.buttons = buttons;