Search code examples
yuiyui3

What is the ideal way to display a datatable inside a YUI View


Given a YUI app with two views, HomePageView & tradedeskPageView, I want to display a datatable in the tradedeskview. TradedeskView is defined with a template like,

  <script id="t-tradedesk" type="text/x-handlebars-template">
     <div id="my-datatable"></div>
  </script>

And the view is defined as below,

YUI().add('tradedeskPageView', function(Y) {

Y.TradedeskPageView = Y.Base.create('tradedeskPageView', Y.View, [], {
    // Compiles the tradedeskTemplate into a reusable Handlebars template.
    template: Y.Handlebars.compile(Y.one('#t-tradedesk').getHTML()),

    initializer: function () {
        var cols = [
            { key: 'id', label: 'ID' },
            { key: 'name', label: 'Name' }
        ];

        var data = [
            { id: 12345, name: 'Srikanth'},
            { id: 12346, name: 'Aditya'}
        ];
        this.table = new Y.DataTable({
            columns: cols,
            data: data
        });

        //this.table.render('#my-datatable'); This is not possible as view is not rendered and node with given id wont exist
    },

    render: function () {
        var content = this.template();         
        this.get('container').setHTML(content); 
        return this;
    }
});
}, '1.0.0', {
  requires: []
});

How should I render table in the required div i.e., #my-datatable in this case.


Solution

  • Give this a go:

    render: function () {
        var content = this.template(),
            container = this.get('container');
    
        container.setHTML(content); 
        this.table.render(container.one('#my-datatable')); //node exists at this point
        return this;
    }
    

    You can init the DataTable in you view's initializer, but only render it when the View itself is rendered