3
votes

I'm having trouble using jquery datatables with Aurelia. I'm trying to import datatables, but with no luck. When I try to initialize it, it gives me error

Unhandled promise rejection TypeError: $(...).dataTable is not a function(…)

My typescript code is following:

import * as $ from 'jquery';
import * as dataTable from 'datatables';
export class App {
router: Router;

constructor() {}
attached() {
    $('#example').dataTable({
        "paginate": true,
        "pageLength": 25
    });
} 
 activate() {  
    console.log("app.activate");
}.... 

Any pointers? Cheers :)

2
i don't know what datatables is, but i would try using import $ from 'jquery' or import 'jquery' and also import 'datatables' - Matthew James Davis

2 Answers

2
votes

You have a couple of issues here that will be causing headaches for you.

Firstly, jQuery exports a default variable of $. So you can do the following to import jQuery inside of a ViewModel:

import 'jquery';

Secondly, the DataTables plugin extends jQuery's library prototype to add itself to the jQuery object. So to get this to work you need to include jQuery first and then the DataTables plugin afterwards.

I couldn't see a default export for client-side usage, so this should give you the following and hopefully functional code:

import 'jquery';
import 'datatables';

Unless I overlooked a particular detail, I believe this should solve the problem. If not, then drop a comment below and we will get it sorted either way.

1
votes

[SOLVED] I got it working by initializing datatable in the activate() method and leaving my imports the way they are...

activate() {  
   datatable();
   console.log("app.activate");
}.... 

Tried a little further, found that this also works...

import * as $ from 'jquery';
import "datatables";
//import * as dataTable from "datatable";

export class DatatablesExample {    
   //activate() {
   //    dataTable();
   //}
    attached() {
        $('#example').dataTable();
    }
}

Quess my problem all along was importing jQuery. But I wonder why the recommended import doesn't work for jquery...

import $ from 'jquery';