เพราะว่าช่วงนี้เขียนเกี่ยวกับ Tabulator อยู่หลายหน้าพอทำไประยะหนึ่งคิดขึ้นมาได้ว่าลืม configuration ไปตัวหนึ่งคือ paginationCounter: "rows" เพราะว่าถ้าไม่ใส่ไว้จะไม่เห็นส่วน Total rows in table ทำให้ต้องกลับไปไล่แก้ทุก ๆ ตัวอย่าง จนคิดถึงคำสอน DRY: don’t repeat yourself ที่แปลว่าอย่าทำอะไรซ้ำซาก copy code ซ้ำไปมา เพราะว่าถ้าแก้ซักอย่างแล้ว ต้องไปตามหา code วนเวียน เวียนวน กันหลาย ๆ ที่ แล้วก็ต้องมาเทสใหม่ ถ้าเกิดว่าสามารถแก้ได้เลย จากที่เดียว จะลดงานแก้ งานเทสออกไปได้เยอะ
assets/Tabulator.common.js
/** * Create a Tabulator table with common configuration * @param {string} selector - DOM selector for the table container * @param {Object} options - Tabulator options (columns, data, etc.) * @returns {Tabulator} - Tabulator instance */
function TabulatorCreate (selector, options = {}) { const defaultConfig = { layout: "fitColumns", movableColumns: true, pagination: true, paginationCounter: "rows", paginationMode: "local", paginationSize: 20, paginationSizeSelector: [10, 20, 25, 50, 100], responsiveLayout: true, // Add more default options as needed }; return new Tabulator (selector, Object.assign ({}, defaultConfig, options)) ;
} // Expose to global scope for inline HTML usage
window.TabulatorCreate = TabulatorCreate;
เรียกใช้โดย include ด้วย<script src="assets/Tabulator.common.js"></script>
หลัง tabulator
จากนั้นแทนที่จะประกาศด้วย
var table = new Tabulator ("#tabulator-table", { //table setup options ... layout: "fitColumns", movableColumns: true, pagination: true, paginationCounter: "rows", paginationMode: "local", paginationSize: 10, paginationSizeSelector: [5, 10, 20, 50], responsiveLayout: true, ...
}) ;
ก็แทนที่ด้วย
var table = TabulatorCreate ("#tabulator-table", { ajaxURL: "../assets/ISO-4217.json", ajaxConfig: "GET", selectable: true, columns: [ { field: "code", title: "Code", width: 80 }, { field: "numeric", title: "Numeric", width: 80 }, { field: "digits", title: "Digits", width: 80 }, { field: "currency", title: "Currency" }, { field: "locations", title: "Locations listed for this currency" } ] }) ;
ค่า config ที่ใช้บ่อย ๆ ใช้เหมือนกันทั้ง project ที่ตรงกับใน function TabulatorCreate จะไม่ต้องใส่ไว้หลายที่และแปลว่าถ้าแก้ค่าพวกนี้อย่างแสดงครั้งละ 10 items เป็นหน้าละ 20 items ก็แก้แค่ที่เดียว ทุกหน้าที่ใช้ function นี้ จะเปลี่ยนมาแสดง 20 รายการต่อหน้าโดยพร้อมเพรียงกัน แต่ถ้าอยากจะให้บางหน้าแสดงไม่เท่าหน้าอื่น ๆ ก็สามารถconfig เฉพาะหน้านั้น ๆ ได้อยู่
อ่านเพิ่มเติม