Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell dataTables to check for updated data in a backbone collection?

I am working on integrating backbone.js with dataTables.

I have a jsfiddle here: http://jsfiddle.net/mwagner72/ekgZk/17/

So far I think I am closest with this setup:

var Chapter = Backbone.Model;
var chapters = new Backbone.Collection();

chapters.add(new Chapter({ page: 9, title: "The End" })); 
chapters.add(new Chapter({ page: 5, title: "The Middle" }));
chapters.add(new Chapter({ page: 1, title: "The Beginning" }));

$('#table_id_3').dataTable({
    "aoColumns": [
        {"sTitle": "Title", "mDataProp": "title"},
        {"sTitle": "Page #","mDataProp": "page"}],
    sAjaxSource: "",
    sAjaxDataProp: "",
    fnServerData: function(sSource, aoData, fnCallback) {
        console.log('here we go');
        fnCallback(chapters.toJSON());
    }
});

This is using my collection as the data source for my dataTable.

My Question:

How do I tell dataTables to check for updated data in the collection?

like image 670
theSociableme Avatar asked Feb 27 '12 20:02

theSociableme


2 Answers

So I figured out the answer with some help from the allen over on the jquery dataTables site. the trick is to use fnReloadAjax() which will redraw your datatable based off of the collection again.

$('#table_id_3').dataTable({
    "aoColumns": [
        { "sTitle": "Title",   "mDataProp": "title" },
        { "sTitle": "Page #",  "mDataProp": "page" }],
    sAjaxSource: "",
    sAjaxDataProp: "",
    fnServerData: function( sSource, aoData, fnCallback ){
        console.log(chapters.toJSON());
        fnCallback(chapters.toJSON());
    }
});

chapters.add(new Chapter({page: 4, title: "The next bunny"}));

var oTable3 = $('#table_id_3').dataTable();
oTable3.fnReloadAjax();

I have a jsfiddle located here: http://jsfiddle.net/mwagner72/ekgZk/

like image 177
theSociableme Avatar answered Oct 20 '22 12:10

theSociableme


You should build a Backbone.View that points to your datatables instance and is associated with your chapters collection. You can use the render function of the view to read from the collection and repopulate the grid. Also, you can bind the "change" event on the collection to trigger the render function of the view, so your collection and your view will be kept in sync.

like image 34
Jake Feasel Avatar answered Oct 20 '22 14:10

Jake Feasel