Mr_LinDowsMac
Mr_LinDowsMac

Reputation: 2702

Where to put a js function that converts a table into a DataTable

I'm using a wonderful library for jQuery named DataTables in Ruby on Rails 4 project. I'm a little confused about where to put a function that converts a tag into a DataTable object (which sets its own classes and ids). I put this in the application.js file, because I would like this function to be available in most the application views, mostly of them are reports, however I don't know if this is the right place. It works, but the in the application.js comments says:

// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the compiled file.

var tabla =  $('.tabla-reporte').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            {
                extend: 'print',
                autoPrint: false,
                customize: function ( win ) {
                    $(win.document.body)
                        .css( 'font-size', '10pt' )
                        .prepend(
                            '<img src="http://datatables.net/media/images/logo-fade.png" style="position:absolute; top:0; left:0;" />'
                        );

                    $(win.document.body).find( 'table' )
                        .addClass( 'compact' )
                        .css( 'font-size', 'inherit' );
                     var medias = win.document.querySelectorAll('[media="screen"]');
                     for(var i=0; i < medias.length;i++){ medias.item(i).media="all" };
                }
            }
        ]
    } );

Apparently there is not problem running that code, because if it doesn't find a class 'tabla-reporte' in the DOM of the current page loaded it won't do anything to it, but I just don't know if this complies with the "rails convention".

Upvotes: 1

Views: 181

Answers (1)

MarsAtomic
MarsAtomic

Reputation: 10696

All you have to do is add the following code to any of your .js files in the assets directory.

$(document).ready(function(){
    $('#myTable').DataTable();
});

This code will turn style any table that has id = "myTable" using DataTables. If you have some table that you don't want this style applied to, then just give it a different id. Protip: if you have multiple tables on the same page that should be styled with DataTables, then you can use class = "myTable" instead.

Don't add anything to your application.js file other than:

//= require dataTables/jquery.dataTables

application.js is meant to store directives, not actual scripts. When your application starts, everything in your assets directory is going to be aggregated into one large script, so you don't have to worry about which .js file contains DataTables code unless you've set up controller specific assets.

Upvotes: 1

Related Questions