TabulatorPlus: Universal StyleTabulatorPlus: Universal Style

เพื่อให้ TabulatorPlus ฉลาดขึ้นและจัดการตัวเองได้ง่ายขึ้นในทุก Framework การเพิ่ม Method สำหรับอัปเดต (Update) ข้อมูลและสถานะตารางเป็นไอเดียที่ดีมากครับ

นี่คือวิธีเพิ่ม Method update และ Method เสริมอื่น ๆ ที่จะช่วยให้คุณควบคุมตารางได้จากภายนอกแบบ Clean Code ครับ


Class TabulatorPlus

import { TabulatorFull as Tabulator } from 'tabulator-tables'; export default class TabulatorPlus extends Tabulator { constructor (el, userConfig = {}, storageKey = null) { const defaultConfig = { layout: "fitColumns", movableColumns: true, pagination: "local", paginationSize: 10, paginationSizeSelector: [10, 25, 50, 100], persistence: storageKey ? { filter: true, page: true, sort: true } : false, persistenceID: storageKey, placeholder: "No Data Available", resizableRows: true, responsiveLayout: "collapse" }; const finalConfig = { ...defaultConfig, ...userConfig }; super (el, finalConfig) ; } /** * 1. Method for updating new data * @param {Array} newData - New dataset to display */ refreshData (newData) { if (newData && Array.isArray (newData)) { // Use the original Tabulator's setData return this.setData (newData) ; } return Promise.reject ("Invalid data format") ; } /** * 2. Method to force redraw the table (e.g. when resizing or opening a modal) */ forceRedraw () { // redraw (true) will resize columns to fit the current container this.redraw (true) ; } /** * 3. Method to clear all filters */ resetFilters () { this.clearFilter (true) ; this.clearHeaderFilter () ; }
}

💡 ทำไมต้องมี Method เหล่านี้ ?

การสืบทอด มาจาก Tabulator ทำให้คุณเรียกใช้ฟังก์ชันดั้งเดิมอย่าง .setData () ได้อยู่แล้ว แต่การสร้าง Method ครอบไว้ มีข้อดีคือ

  • Semantic Meaning: ชื่อฟังก์ชันอย่าง refreshData () สื่อสารความหมายได้ชัดเจนกว่าในเชิงธุรกิจ
  • Safety Check: คุณสามารถดักจับ Error หรือเช็คประเภทข้อมูล ก่อนส่งให้ Library หลักทำงานได้
  • One-Stop Service: หากในอนาคตคุณอยากให้ทุกครั้งที่อัปเดตข้อมูล ต้องมีการ log ค่า หรือเปลี่ยนสี Header คุณก็แค่มาแก้ที่ refreshData ในไฟล์เดียว

ตัวอย่างการเรียกใช้งาน

ไม่ว่าคุณจะใช้ Framework ไหน การเรียกใช้จะดูเป็นระเบียบขึ้นมากครับ

// สร้าง Instance
const myTable = new TabulatorPlus ("#table-id", {}, "user-123") ; // เมื่อได้รับข้อมูลใหม่จาก API
api.getData () .then (data => { myTable.refreshData (data) ; // เรียกผ่าน Method ที่เราสร้างใหม่
}) ; // เมื่อ User กดปุ่ม "ล้างค่าการค้นหา"
$ ("#btn-reset") .on ("click", () => { myTable.resetFilters () ;
}) ;

อ่านเพิ่มเติม