aureliajqwidget

Using jQWidgets in Aurelia


I'd like to use the jqxGrid widget in an Aurelia project, but I'm not sure how to adapt their example (below) to work in an Aurelia View/View-Model component.

See it run here.

<!DOCTYPE html>
<html lang="en">
<head>
    <title id='Description'>This example shows how to create a Grid from Array data.</title>
    <link rel="stylesheet" href="../../jqwidgets/styles/jqx.base.css" type="text/css" />
    <script type="text/javascript" src="../../scripts/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxcore.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxdata.js"></script> 
    <script type="text/javascript" src="../../jqwidgets/jqxbuttons.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxscrollbar.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxmenu.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxgrid.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxgrid.selection.js"></script> 
    <script type="text/javascript" src="../../jqwidgets/jqxgrid.columnsresize.js"></script> 
    <script type="text/javascript" src="../../scripts/demos.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            // prepare the data
            var data = new Array();
            var firstNames =
            [
                "Andrew", "Nancy", "Shelley", "Regina", "Yoshi", "Antoni", "Mayumi", "Ian", "Peter", "Lars", "Petra", "Martin", "Sven", "Elio", "Beate", "Cheryl", "Michael", "Guylene"
            ];
            var lastNames =
            [
                "Fuller", "Davolio", "Burke", "Murphy", "Nagase", "Saavedra", "Ohno", "Devling", "Wilson", "Peterson", "Winkler", "Bein", "Petersen", "Rossi", "Vileid", "Saylor", "Bjorn", "Nodier"
            ];
            var productNames =
            [
                "Black Tea", "Green Tea", "Caffe Espresso", "Doubleshot Espresso", "Caffe Latte", "White Chocolate Mocha", "Cramel Latte", "Caffe Americano", "Cappuccino", "Espresso Truffle", "Espresso con Panna", "Peppermint Mocha Twist"
            ];
            var priceValues =
            [
                "2.25", "1.5", "3.0", "3.3", "4.5", "3.6", "3.8", "2.5", "5.0", "1.75", "3.25", "4.0"
            ];
            for (var i = 0; i < 200; i++) {
                var row = {};
                var productindex = Math.floor(Math.random() * productNames.length);
                var price = parseFloat(priceValues[productindex]);
                var quantity = 1 + Math.round(Math.random() * 10);
                row["firstname"] = firstNames[Math.floor(Math.random() * firstNames.length)];
                row["lastname"] = lastNames[Math.floor(Math.random() * lastNames.length)];
                row["productname"] = productNames[productindex];
                row["price"] = price;
                row["quantity"] = quantity;
                row["total"] = price * quantity;
                data[i] = row;
            }
            var source =
            {
                localdata: data,
                datatype: "array",
                datafields:
                [
                    { name: 'firstname', type: 'string' },
                    { name: 'lastname', type: 'string' },
                    { name: 'productname', type: 'string' },
                    { name: 'quantity', type: 'number' },
                    { name: 'price', type: 'number' },
                    { name: 'total', type: 'number' }
                ]
            };
            var dataAdapter = new $.jqx.dataAdapter(source);

            $("#jqxgrid").jqxGrid(
            {
                width: 850,
                source: dataAdapter,
                columnsresize: true,
                columns: [
                  { text: 'Name', datafield: 'firstname', width: 120 },
                  { text: 'Last Name', datafield: 'lastname', width: 120 },
                  { text: 'Product', datafield: 'productname', width: 180 },
                  { text: 'Quantity', datafield: 'quantity', width: 80, cellsalign: 'right' },
                  { text: 'Unit Price', datafield: 'price', width: 90, cellsalign: 'right', cellsformat: 'c2' },
                  { text: 'Total', datafield: 'total', cellsalign: 'right', cellsformat: 'c2' }
                ]
            });
        });
    </script>
</head>
<body class='default'>
    <div id='jqxWidget'>
        <div id="jqxgrid">
        </div>
    </div>
</body>
</html>

According to the example above, everything is done through HTML script tags, which don't seem to work in the HTML template elements used in Aurelia Views. I assume I'd have to import the required jqwidgets files into the View-Model with JSPM, but I haven't the slightest idea how to do that.

Could anyone help me figure out how to wire up the above example code into an Aurelia component? (If it helps, I have an empty, editable Aurelia project skeleton running here https://gist.run/?id=6f38a1211eeecafe74c4dd4c960fc2d6&sha=d9959ac0f4d7ad9f3c8385b7b78f648adfc91e11).


Solution

  • I have created a sample app based on the aurelia-skeleton-navigation, you can find this here. Let me walk you through the relevant steps.

    First you need to install the jqwidgets: jspm install jqwidgets=github:jqwidgets/jQWidgets

    Make sure that you have install JSPM's css plugin as well: jspm install css.

    In app.html we can load the CSS part of jqwidgets: <require from="jqwidgets/jqwidgets/styles/jqx.base.css!"></require>. Note the exclamation mark at the end, which instructs SystemJS to load the css file using the css plugin. This

    Then you could create a my-grid custom element by creating two files: my-grid.html and my-grid.js.

    my-grid.html could look something like:

    <template>
      <div ref="container"></div>
    </template>
    

    Here you see the ref attribute, which is Aurelia-specific code, and it will create a property called container on the view-model (my-grid.js), containing a reference to the div element. This is very handy as we can use this reference to initialize the grid without having to use jQuery.

    creating my-grid.js is a little bit more work

    import 'jquery';
    import 'jqwidgets/jqwidgets/jqxcore';
    import 'jqwidgets/jqwidgets/jqxdata';
    import 'jqwidgets/jqwidgets/jqxbuttons';
    import 'jqwidgets/jqwidgets/jqxscrollbar';
    import 'jqwidgets/jqwidgets/jqxmenu';
    import 'jqwidgets/jqwidgets/jqxgrid';
    import 'jqwidgets/jqwidgets/jqxgrid.aggregates';
    import 'jqwidgets/jqwidgets/jqxgrid.columnsreorder';
    import 'jqwidgets/jqwidgets/jqxgrid.columnsresize';
    import 'jqwidgets/jqwidgets/jqxgrid.edit';
    import 'jqwidgets/jqwidgets/jqxgrid.export';
    import 'jqwidgets/jqwidgets/jqxgrid.filter';
    import 'jqwidgets/jqwidgets/jqxgrid.grouping';
    import 'jqwidgets/jqwidgets/jqxgrid.pager';
    import 'jqwidgets/jqwidgets/jqxgrid.selection';
    import 'jqwidgets/jqwidgets/jqxgrid.sort';
    import 'jqwidgets/jqwidgets/jqxgrid.storage';
    import {bindable} from 'aurelia-framework';
    
    export class MyGridCustomElement {
      @bindable gridData;
    
      attached() {
        let source = {
          localdata: this.gridData,
          datatype: 'array',
          datafields:
          [
              { name: 'firstname', type: 'string' },
              { name: 'lastname', type: 'string' },
              { name: 'productname', type: 'string' },
              { name: 'quantity', type: 'number' },
              { name: 'price', type: 'number' },
              { name: 'total', type: 'number' }
          ]
        };
    
        let dataAdapter = new $.jqx.dataAdapter(source);
    
        $(this.container).jqxGrid({
          width: 850,
          source: dataAdapter,
          columnsresize: true,
          columns: [
            { text: 'Name', datafield: 'firstname', width: 120 },
            { text: 'Last Name', datafield: 'lastname', width: 120 },
            { text: 'Product', datafield: 'productname', width: 180 },
            { text: 'Quantity', datafield: 'quantity', width: 80, cellsalign: 'right' },
            { text: 'Unit Price', datafield: 'price', width: 90, cellsalign: 'right', cellsformat: 'c2' },
            { text: 'Total', datafield: 'total', cellsalign: 'right', cellsformat: 'c2' }
          ]
        });
      }
    }
    

    A few things are happening here. First, using Aurelia's naming conventions when naming the class MyGridCustomElement, we can use this custom element with <my-grid>.

    Another thing you see is the large amount of import statements. This will pull in all parts of the jqxgrid. We need to tell JSPM to load these modules as Global, as JSPM will try and load these as AMD which will not work.

    Since we'd like to pass data to the <my-grid> custom element, we need to set up a property that we can then bind to. This can be done by decorating a with the @bindable decorator.

    It is recommended to initialize jQuery components from the attached() lifecycle callback. In my-grid.html we added the ref="container" attribute, which allows us to initialize the grid from the view-model using the container property: $(this.container).jqxGrid({.

    At this point the <my-grid> custom element is set up and we can start using it.

    In any view, and I have chosen to do this in the welcome.html view, the following will allow you to use the <my-grid> custom element:

    <template>
      <require from="./my-grid"></require>
    
      <my-grid grid-data.bind="data"></my-grid>
    </template>
    

    The <require> tag will pull in our custom element so that we can use it from this view. We would now like to pass some data to this custom element. In my-grid.js we declared a property @bindable which was the gridData property. Here we must convert it to kebab-case (gridData -> grid-data). And we databind the gridData property to the data property which exists in the welcome.js file.

    At this point we should be done, although we need to instruct JSPM to load jqxgrid using the Global module format (as it does not load correctly using the default AMD format). You can see the necessary configuration to do so in config.js.