better-staridc-MNBT
1/**
2 * @author: Dennis Hernández
3 * @webSite: http://djhvscf.github.io/Blog
4 * @update zhixin wen <wenzhixin2010@gmail.com>
5 */
6
7const rowAttr = (row, index) => ({
8 id: `customId_${index}`
9})
10
11$.extend($.fn.bootstrapTable.defaults, {
12 reorderableRows: false,
13 onDragStyle: null,
14 onDropStyle: null,
15 onDragClass: 'reorder_rows_onDragClass',
16 dragHandle: '>tbody>tr>td',
17 useRowAttrFunc: false,
18 onReorderRowsDrag (row) {
19 return false
20 },
21 onReorderRowsDrop (row) {
22 return false
23 },
24 onReorderRow (newData) {
25 return false
26 }
27})
28
29$.extend($.fn.bootstrapTable.Constructor.EVENTS, {
30 'reorder-row.bs.table': 'onReorderRow'
31})
32
33$.BootstrapTable = class extends $.BootstrapTable {
34 init (...args) {
35 if (!this.options.reorderableRows) {
36 super.init(...args)
37 return
38 }
39
40 if (this.options.useRowAttrFunc) {
41 this.options.rowAttributes = rowAttr
42 }
43
44 const onPostBody = this.options.onPostBody
45 this.options.onPostBody = () => {
46 setTimeout(() => {
47 this.makeRowsReorderable()
48 onPostBody.call(this.options, this.options.data)
49 }, 1)
50 }
51
52 super.init(...args)
53 }
54
55 makeRowsReorderable () {
56 this.$el.tableDnD({
57 onDragStyle: this.options.onDragStyle,
58 onDropStyle: this.options.onDropStyle,
59 onDragClass: this.options.onDragClass,
60 onDragStart: (table, droppedRow) => this.onDropStart(table, droppedRow),
61 onDrop: (table, droppedRow) => this.onDrop(table, droppedRow),
62 dragHandle: this.options.dragHandle
63 })
64 }
65
66 onDropStart (table, draggingTd) {
67 this.$draggingTd = $(draggingTd).css('cursor', 'move')
68 this.draggingIndex = $(this.$draggingTd.parent()).data('index')
69 // Call the user defined function
70 this.options.onReorderRowsDrag(this.data[this.draggingIndex])
71 }
72
73 onDrop (table) {
74 this.$draggingTd.css('cursor', '')
75 const newData = []
76 for (let i = 0; i < table.tBodies[0].rows.length; i++) {
77 const $tr = $(table.tBodies[0].rows[i])
78 newData.push(this.data[$tr.data('index')])
79 $tr.data('index', i)
80 }
81
82 const draggingRow = this.data[this.draggingIndex]
83 const droppedIndex = newData.indexOf(this.data[this.draggingIndex])
84 const droppedRow = this.data[droppedIndex]
85 const index = this.options.data.indexOf(this.data[droppedIndex])
86 this.options.data.splice(this.options.data.indexOf(draggingRow), 1)
87 this.options.data.splice(index, 0, draggingRow)
88
89 // Call the user defined function
90 this.options.onReorderRowsDrop(droppedRow)
91
92 // Call the event reorder-row
93 this.trigger('reorder-row', newData)
94 }
95}