Home > JavaScript, Knockout.js, koGrid, TypeScript > koGrid: Get reference to grid for direct manipulations

koGrid: Get reference to grid for direct manipulations

January 26th, 2017 Admin Leave a comment Go to comments

    Having used the koGrid on the page, sometimes you may need to manipulate with the grid directly, for example, to programmatically select or deselect items and so on. For this you need to get a reference to the grid instance first. The koGrid supports plugins to enhance and extend grid’s capabilities. Each plugin should expose the onGridInit method being called from the koGrid-binding and fed with the grid instance, which can be saved and used later. Below is a fragment of the koGrid-binding where the plugins are being initialized:

// koGrid-2.1.1.debug.js
ko.bindingHandlers['koGrid'] = (function () {
  return {
    'init': function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
       var options = valueAccessor();
       ...
       var grid = new window.kg.Grid(options);
       ...
       //initialize plugins
       $.each(grid.config.plugins, function (i, p) {
          if (typeof p.onGridInit === 'function') {
             p.onGridInit(grid);
          }
       });
       ...
       return { controlsDescendantBindings: true };
    }
  };
}());

Let’s create a plugin to capture the reference to the grid. The following simple typescript class keeps the reference and exposes it to outer code. Note the use of ko.utils.domNodeDisposal.addDisposeCallback to release the reference if the grid disappears from the DOM-model (for example, being wrapped in if- or with-bindings).

// typescript
export class KoGridRef {

  public grid = null;

  public onGridInit(grid) {
    // save the reference
    this.grid = grid;

    var self = this;
    // hook up the node removing to release the reference to the grid instance
    ko.utils.domNodeDisposal.addDisposeCallback(grid.$root[0], function() {
      self.grid = null;
    });
  }
}

Below is how to declare, attach and use the plugin

// typescript

// declare
private gridRef: KoGridRef = new KoGridRef();

// attach
public koGridOptions = ko.pureComputed(() => {
  return {
    data: this.items, // observable array of data
    selectedItems: this.selectedItems, // observable array to store selected items
    plugins: [gridRef], // array of plugins
    ...
  }
});

// use
public get grid() { // property to return the grid instance
  return this.gridRef.grid;
}	

public selectAll(grid: any, state: boolean) { // method to select or deselect all items
  grid.allSelected(state);
}
...
this.selectAll(this.grid, Math.random() >= 0.5); // randomly select or deselect all items
...
Related posts:
 
  1. No comments yet.
  1. No trackbacks yet.