persistent variables

persistent variables

mbroadstmbroadst Posts: 14Questions: 0Answers: 0
edited November 2011 in General
Greetings,
I'm using DataTables in a fairly complex project, and was wondering if anyone has come across a need to maintain stateful data associated with a datatable instance. The site itself never leaves the first page loaded, instead other page elements are dynamically loaded in using jQuery's load(...) method. The specific problem I am trying to tackle right now is how to maintain a "selection model" associated with a table to keep track of selected items. The only solution I have found so far is to create a global variable (which I gather is the same as assigning the variable to the window object) and then accessing that later. Is there a way for me to assign a custom property to a datatable object? Ideally, I would be able to do something like this:
[code]
$(document).ready(function() {
var table = $('#my_table').dataTable( options );
table.selection_model = new Array();
});
[/code]

and from some other page:
[code]
var table = $('#my_table').dataTable();
console.log(table.selection_model);
[/code]

this doesn't seem to work currently, I imagine because of some scope confusion.

Replies

  • mbroadstmbroadst Posts: 14Questions: 0Answers: 0
    I'm surprised to see that nobody has run into this issue. What do other people do to maintain a model of selected items?
  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    edited November 2011
    Is there something you don't like about the global variable? Or did you just want something more specifically linked to a datatable instance?

    i would imagine you could extend DT the same way you would with plug-ins and add your storage variable.

    http://www.datatables.net/blog/Creating_feature_plug-ins
  • allanallan Posts: 63,535Questions: 1Answers: 10,475 Site admin
    The result of $().dataTable(); is an array created by jQuery, rather than a proper instance of DataTables (like if you were to do something such as "new DataTable()"). As such, unless you store that array reference, then anything that gets attached to it will be lost (you get a new array each time you call the constructor).

    What you can do is attach to the DataTables settings object, which is persistent. For example, modifying your example above:

    [code]
    $(document).ready(function() {
      var table = $('#my_table').dataTable( options );
      table.fnSettings().selection_model = new Array();
    });
    [/code]

    [code]
    var table = $('#my_table').dataTable();
    console.log(table.fnSettings().selection_model);
    [/code]

    Like fbas suggests, if you are going to be using this a lot, I'd suggest creating a plug-in API method which will wrap this up into a getter / setter function to make things a little cleaner.

    Allan
This discussion has been closed.