detecting old dataTable() object vs. new DataTable() object

detecting old dataTable() object vs. new DataTable() object

carteriiicarteriii Posts: 25Questions: 1Answers: 0

I'm upgrading an older site from 1.9.x to 1.10.x and have several tables to migrate. I intend to migrate the tables one at a time so I'd like to abstract some of my code to work with both versions. So for example, assume I have both versions initialized such as:

var oldStyle = $('#old').dataTable();
var newStyle = $('#new').DataTable();

Now assume I want to call the same function passing either table...

genericFunction(oldStyle);
genericFunction(newStyle);

And now I move onto totally fictitious pseudo-code which demonstrates what I'd like to do. I'd like to be able to test "myTable" to know if it is an old object or a new API object. Note here that I'm using "typeof", which does not work, but I'm just trying to show the concept of what I'd like to do.

function genericFunction(myTable)
{
  if (typeof(myTable) == "old dataTable jquery object") {
    .... <use old functions>...
  } elseif (typeof(myTable) == "new DataTable API object") {
    .... <use new APIs>
   }
}

Clearly I can't just use typeof() and get what I want since both are "objects". I have debated about trying to call one style and simply using an exception to catch the error, but it seems like there is probably a cleaner way, more along the lines of typeof().

Answers

  • allanallan Posts: 61,920Questions: 1Answers: 10,153 Site admin

    You could use instanceof rather than typeof for this:

    if ( myTable instanceof $.fn.dataTable.Api ) {
      ... new API method
    }
    else {
      ... old API
    }
    

    Going one step further you could detect jQuery style objects (the old API) and convert them to the new if you wanted:

    var api = myTable;
    
    if ( ! ( myTable instanceof $.fn.dataTable.Api ) ) {
      api = myTable.api();
    }
    
    ... use new API method
    

    Regards,
    Allan

  • carteriiicarteriii Posts: 25Questions: 1Answers: 0

    Allan, you are the best. Thank you. I didn't realize I could just call myTable.api() to get the API object itself from the old table. That's perfect.

This discussion has been closed.