Skip to content

Instance methods ​

A grid instance (new Datagrid(…), Datagrid.get(el), find(name)) implements DatagridApi. Methods that change state (search, page, sort, filters…) load data themselves; you never call refresh() or draw().

js
const grid = Datagrid.get("#agents");
grid.batch(() => {
  grid.sort([["date", "desc"]]);
  grid.filters({ unit: "R.P.D." });
});
await grid.reload();

Data loading ​

MemberReturnsDescription
load()Promise<void>Loads with the current query. Fires beforeLoad (cancelable). The last request wins: a running request is aborted and stale responses are dropped (matched by sequence, never by the server's draw). In client mode, once data is loaded, it recomputes the view locally without a request.
reload({ keepPage?, silent? })Promise<void>Loads again. Goes back to page 1 unless keepPage: true. silent: true skips the busy overlay. Array and DOM sources re-run search, sort and paging over the current rows, keeping setData() / addRows() / removeRow() changes; fetchAll refetches. With errorMode: "throw" the promise rejects on failure.
setData(rows)voidClient mode: replaces the rows and re-renders.
addRows(rows, { keepPage? })voidClient mode: appends rows and jumps to the last page unless keepPage: true. Ignored in server mode (a development notice is printed); change the data on the server and reload().
removeRow(key)voidRemoves the row with this key: from the data (client) or from the current page until the next load (server).
refreshRow(key, row?)voidRe-renders one row in place, optionally replacing its data object first. Row mutators run again.
exportRows(scope?)Promise<Row[]>Rows for an export. "page" (default): the current view. "all": every filtered row; client mode computes them locally, server mode sends one request with pageSize = maxPageSize (request middleware included).
lastResponse()unknownRaw JSON body of the last load (server sources and fetchAll); null for array and DOM sources.
lastRequestParams()objectPage parameters of the request behind the rows on screen, as they reached the wire: filter panel, toggles, params, after every middleware. With ssp / yajra also non-column filters() and whatever a data function added; the protocol's own fields (draw, columns, order, start, length, search) and _token are left out. {} for local sources. Use it to rebuild "all matching" on the server.

State: getters and setters ​

Each setter returns the current value, so calling it without an argument reads it.

MemberReturnsDescription
search(text?)stringSets the search text, goes to page 1, loads and announces the result count. Fires search. Also updates the toolbar box.
page(n?)numberGoes to page n (1-based), clamped to the page count (open-ended when the total is unknown). Fires beforePage (cancelable) and page; scrolls the table to the top. Before the first load it only stores the value.
pageSize(n?)numberSets rows per page and goes to page 1. Values above maxPageSize or below 0 are clamped (DG013); -1 is "All" where the protocol allows it. 0 means paging is off. Fires pagesize.
sort(spec?)SortSpec[]Sets the sort: [["date", "desc"]] or [{ key: "date", dir: "desc" }]; [] clears it. Goes to page 1, announces the new order. Fires beforeSort (cancelable) and sort.
filters(patch?)Readonly<Record<string, unknown>>Merges patch into the filters (null, "" or [] removes a key), goes to page 1 and loads. See Filters.
query()QueryThe current request payload, see Query.
status()GridStatusLoading status, totals and the last error, see GridStatus.
batch(fn)voidRuns fn with loads and sort announcements suppressed, so several setters don't each fire a request. Nothing loads afterwards on its own: call reload() once fn returns.
stateContributions()ReadonlyArray<StateContribution>Parts registered with ctx.state() by modules (what stateSave persists).

Filters ​

filters() is the one filter store for every filter UI (filter panels, column filters, your own code).

ValueClient mode
string / number / booleanequals (compared as strings)
arrayany of the values
{ op, value }typed operator: eq, ne, gt, gte, lt, lte, between, in, notIn, contains, notContains, starts, ends, empty, notEmpty
(value, row) => booleanpredicate

In client mode a key that is a column key compares the cell value; any other key reads that path of the row. On a server source the protocol encodes the filters (functions are never sent):

ProtocolHow filters travel
ssp() / yajra()Keys that are not column keys: extra form parameters (unit=R.P.D.). { op, value } on a searchable column: columns[i][columnControl] (no between / notIn). A plain value on a column key is an equality: an anchored, escaped regex in columns[i][search][value] (^R\.P\.D\.$, regex=true; an array becomes ^a$|^b$). Filters on columns with searchable: false are not sent (development notice).
dgp()filters: { key: { op, value } }; a plain value becomes eq, an array in.
laravelPaginator()Query parameters key=value; typed filters send their value, so only eq and in mean what they say (the column filter menu offers only those).

Query ​

FieldTypeDescription
pagenumber1-based page.
pageSizenumberRows per page; 0 = paging off, -1 = all.
sortSortSpec[]{ key, dir } entries.
searchstringToolbar search text.
filtersRecord<string, unknown>Copy of the filter store.
columnsResolvedColumn[]Columns in definition order (the wire order), with resolved title, sortable, searchable, visible, hideable, exportable, defaultVisible, index.
sortDefaultbooleanfalse only when the grid was created with an explicit sort: []. While it is true, an empty sort on the SSP wire sends the first column ascending — also after the sort was cleared at runtime.
pristinebooleanThe query is still the one the grid was configured with (nothing restored or changed yet).

GridStatus ​

FieldTypeDescription
status"idle" | "loading" | "reloading" | "ready" | "error"idle: load: "manual" before the first load. loading: first load. reloading: later loads (the rows stay on screen).
loadedbooleanAt least one load succeeded.
totalnumber | nullRecords before filtering; null when the server doesn't count.
filterednumber | nullRecords after search and filters.
hasMoreboolean | nullNext page exists (servers that don't count, e.g. simplePaginate).
errorDatagridError | nullLast error: { kind, status, message, detail?, retryable, raw? }. Cleared by the next successful load.

Rows ​

MemberReturnsDescription
rows()Row[]Client mode: every row. Server mode: the current page.
viewRows()Row[]The rows currently rendered (after client search, filters, sort and paging; or the server page).
keyOf(row)stringThe row's key (rowKey, else id, else DT_RowId, else a position key with DG003).
rowByKey(key)Row | undefinedRow object for a key, among the loaded rows.

Columns ​

MemberReturnsDescription
columns()ReadonlyArray<ResolvedColumn>Columns in display order (after reordering). query().columns keeps the definition order.
setColumns(defs)voidReplaces the column definitions, drops sort entries for missing keys, re-renders the header, fires columnchange and reloads keeping the page.
setColumnVisible(key, visible)voidShows or hides a column without a request. Hiding a column with hideable: false is refused. Fires columnchange.
columnOrder(keys?)string[]Sets the display order (keys not listed keep their relative order at the end; special and sticky columns keep their slots) and returns the full order. The request keeps the definition order. Fires columnchange.

Events ​

MemberReturnsDescription
on(type, fn)() => voidSubscribes to a grid event; returns the unsubscribe function. See Events.
emit(type, detail)booleanFires an event (listeners + a dg:<type> DOM event on the root). Returns false when a listener cancelled it; events whose name starts with before get a cancel() method. For modules that publish their own events.
delegate(type, selector, fn)() => voidDOM event delegation on the root with row context: fn(event, { row, key, tr, td, column }). Only fires for rows of this grid. Returns the remover.

Actions and host adapters ​

MemberReturnsDescription
action(url, options?)Promise<unknown>Row action helper: optional confirm → same-origin request with X-CSRF-TOKEN (from meta[name=csrf-token]), Accept: application/json and X-Requested-With → success notification (the response's message, else messages.actionDone) → reload({ keepPage: true }). Resolves with the parsed response, undefined when the confirm was declined. Errors are notified and rethrown; 401/419 or a redirect to a login page also fire sessionexpired and call the onSessionExpired adapter. A redirect to any other page (a classic return back()) counts as success. A 2xx whose body reports a failure counts only through an isError rule (below).
notify(kind, message)voidUses the notify host adapter; without one it announces the message in the live region and shows errors as a banner above the table. kind: "success" | "error" | "info".
confirm(message, options?)Promise<boolean>Uses the confirm host adapter, else the built-in <dialog>. Options: title, tone ("danger" | "default"), confirmLabel, cancelLabel, subject.

action() options:

OptionTypeDefaultDescription
method"GET" | "POST" | "PUT" | "PATCH" | "DELETE""POST"Anything else throws.
bodyRecord<string, unknown> | FormData | null—Objects are sent as JSON (not for GET); FormData as is.
confirmstring | { message, title?, tone?, confirmLabel?, cancelLabel?, subject? }—Ask first.
successstring | falseresponse messageSuccess text; false = no notification.
reloadfalse | { keepPage?, silent? }{ keepPage: true }Reload after success.
headersRecord<string, string>—Extra request headers.
isError(body, res) => boolean | string | nullconfigure({ isError })Decides whether a 2xx response failed after all ({ status: false, error }). Truthy = failure: the error is notified and thrown (kind: "server", the body in raw) and nothing reloads; a string is the message, true uses messages.actionFailed. Without a rule every 2xx is a success.

The URL must be same-origin http(s).

Modules and lifecycle ​

MemberReturnsDescription
use(module | modules[])thisAttaches modules after construction and re-renders. A data source here replaces the default one; a second explicit source throws DG008. remount() keeps chained modules.
module(factoryOrDef)API or nullTyped access to a module's API: grid.module(stateSave). null when the module is not attached.
destroy()voidAborts requests, destroys modules (in reverse order), fires destroy and restores the table exactly as it was (<thead>, <tbody> rows, attributes, position). Idempotent.
remount(table?)DatagridApidestroy() + a new grid with the same constructor options, on the same or another table (for DOM morphing frameworks). Modules attached later with use() come along.

Properties ​

PropertyTypeDescription
rootHTMLElementThe .dg wrapper around the table.
tableHTMLTableElementYour table (same element, enhanced in place).
namestring | undefinedThe name option.
messagesMessagesThe merged UI strings.
localestringResolved locale.
mode"client" | "server"From the data source.
maxPageSizenumberResolved limit.

Module APIs ​

Each module installs its API on the grid under its module name. In TypeScript, grid.module(factory) returns the typed API.

ModulePropertyAPI
stateSave()grid.statekey (storage key), save(), read() → stored payload or null, clear(), reset() → Promise<void> (initial view + reload)
colVis()grid.colVisopen(), close(), toggle(), reset(), count() → { visible, total }
colReorder()grid.colReorderorder() → keys, move(key, to), reset(), movable() → columns, messages
columnFilters()grid.columnFiltersopen(key), current (key of the open filter or null)
filterPanel()grid.filterPanelvalues(), raw(), set(patch, { reload? }), reset(), apply()
urlSync()grid.urlSynclink() → shareable URL of the current view
softDeletes()grid.softDeletesactive(), toggle(on?)
actions()grid.actionsrun(id, key), open(key) (row menu), items(key) → resolved items with disabled reasons
selection()grid.selectionget(), keys(), payload(), count(), isAll(), isSelected(key), select(keys), deselect(keys), toggle(key), clear(), selectPage(), deselectPage(), selectAllMatching()
excel()grid.exceldownload(), blob()
csv()grid.csvdownload(), text()
print()grid.printopen()
responsive()grid.responsivecollapsed() → keys of collapsed columns, refit(), toggle(rowKey, open?) (detail row)
lazyColumns()grid.lazyColumnsrequested() → lazy keys sent with the last request, visible() → lazy keys visible now, param (the request parameter name)
stickyHeader()grid.stickyHeaderstuck(), refresh()
keyboardGrid()grid.keyboardGridposition(), focus(row, col)
rowReorder()grid.rowReorderenabled(), move(key, to) → Promise<boolean>
multiSort()grid.multiSorttoggle(key)
autoRefresh()grid.autoRefreshrunning(), start(), stop(), tick()
filterPresets()grid.filterPresetsactive() → id of the matching preset or null, apply(id, { reload? })
metaBind()grid.metaBindrefresh()
footer()grid.footervalues(), refresh()
button.reload()grid.reloadButtonel (the button)
button.resetState()grid.resetStateButtonel
button.custom() / button.group()grid[name]el; name defaults to button<N> / buttonGroup<N>

A module attached with can: false still answers on its property: every call is a no-op.

Gotchas ​

  • reload() keeps local edits: on array and DOM sources it re-runs search, sort and paging over the current rows (including setData() / addRows() / removeRow() changes). Only fetchAll fetches again.
  • batch() loads nothing: follow it with reload().
  • grid.module(button.custom) returns null: custom buttons and groups are registered under their name; read them as grid[name].
  • addRows() and setData() are for client mode; addRows() is ignored on a server source. Change the data on the server and reload({ keepPage: true }).

Released under the MIT License.