天天看點

bootstrap-treeview 自定義添加節點方法

        bootstrap-treeview官方沒有給出動态添加子節點和子節點集合的方法, 當需要點選父節點再去從背景擷取其子節點時, 需要使用者自定義動态加載子節點方法. 本文自定義了添加節點集合方法, 用于一次添加多個子節點. 步驟如下.

1. 添加方法入口

        在Tree主函數return {/*在這裡添加addNewNodes的入口*/} 處添加代碼

// Add Nodes Method
            addNewNodes: $.proxy(this.addNewNodes, this),           

        添加結果如下:

return {
            // Options (public access)
            options: this.options,

            // Initialize / destroy methods
            init: $.proxy(this.init, this),
            remove: $.proxy(this.remove, this),

            // Add Method
            addNewNodes: $.proxy(this.addNewNodes, this),

            // Get methods
            getNode: $.proxy(this.getNode, this),
            getParent: $.proxy(this.getParent, this),
            getSiblings: $.proxy(this.getSiblings, this),
            ......
        };
    };           

2. 編寫添加節點方法

/**
	 * 給節點添加子節點
	 * @param {Object|Number} identifiers - A valid node, node id or array of node identifiers
	 * @param {optional Object} options.node; 
	 */
	Tree.prototype.addNewNodes = function (identifiers, options) {
	    this.forEachIdentifier(identifiers, options, $.proxy(function (node, options) {
	            this.setNewNodes(node, options);
	    }, this));

	    this.setInitialStates({ nodes: this.tree }, 0);
	    this.render();
	};

	/**
	 *  添加子節點
	 */
	Tree.prototype.setNewNodes = function (node, options) {
	    if (node.nodes == null) node.nodes = [];
	    if (options.nodes) {
	        $.each(options.nodes, function (index,option) {
	            node.nodes.push(option);
	        })
	    }
	};           

3 使用

// 當觸發展開節點事件時, 發送ajax請求到背景擷取子節點清單, 然後使用                addNewNodes動态添加到treeview中      
onNodeExpanded: function(event, node) {
        	var childrenIds = listChildrenIds(node);
        	if (childrenIds.length > 0) {
        		return;
        	}
        	var nodeId = node.nodeId;
        	ajaxGet({
        		url: contextPath + "/departments/" + node.code + "/list",
        		success: function(res) {
        			checkableTree_departmentManage.treeview("addNewNodes", [nodeId, { nodes: res.data }]);
        		}
        	})
        },             

展示, 當加載時, 隻加載一級部門, 如下圖:

bootstrap-treeview 自定義添加節點方法

點選一級部門, 再去背景請求一級部門的子部門, 如下:

bootstrap-treeview 自定義添加節點方法