How do I run custom JavaScript on emberjs handlebar template view?


#1

i am new in emberjs, i want to implement hansontable in my handlebar emberjs view, my view code is given below

<script type=“text/x-handlebars” data-template-name=“clex/sc”> <div id=“spread-sheet” style=“width: 100%;”></div> </script>

currently i attaching hansontable to #spread_sheet div by using javascript on document ready function, example given below

<script>$(document).ready(function() {

var data = [[""]], spread_sheet = $("#spread_sheet");

var validateDate = /^[0-9]{2}-[0-9]{2}-[0-9]{4}$/; // mm-dd-yyyy

spread_sheet.handsontable({
    autoWrapCol: true,
    autoWrapRow: true,
    columns: [
        {data: 0},
        {data: 1, validator: validateDate},
        {data: 2},
        {data: 3},
        {data: 4},
        {data: 5, validator: validateDate},
        {data: 6},
        {data: 7, validator: validateDate},
        {data: 8},
        {data: 9},
        {data: 10},
        {data: 11},
        {data: 12},
        {data: 13},
        {data: 14}
    ],
    colWidths: window.innerWidth*.12,
    contextMenu: true,
    currentRowClassName: "row_selected",
    data: data,
    fixedColumnsLeft: 1,
    height: window.innerHeight - 32,
    manualColumnMove: true,
    manualColumnResize: true,
    minSpareCols: 2,
    minSpareRows: 80,
    outsideClickDeselects: false,
    persistentState: true,
    rowHeaders: true,
    stretchH: "last",
    width: window.innerWidth
});</script>

but it dont work with emberjs handlebar template

i want to implement it in emberjs but i dont know how to add this in handlebar template ? i feel same problem when i tried to implement d3js for barchart ?

can i do it with “didInsert” of view object ?


#2

Yes, you can use the didInsertElement event to be sure that the element has been added to the DOM and available for manipulation.


#3

Probably want something like this:

App.HandsontableView = Ember.View.extend({
    classNames: ['spread-sheet'],

    didInsertElement: function () {
        var data = [['']];

        this.$('.spread-sheet').handsontable({
             data: data,
             // and so on....
        });
    }
});

Then you can do in template:

{{view App.HandsontableView}}

Note that this is replacing the

<div id="spread_sheet"></div>

that you had previously…since the view itself has a div, we can just render into the view itself by assigning a proper class name.


#4

thanx tristanpendergr i also get another way, here


#5

Yup, that and mine are pretty much equivalent. It’s just a style thing, but I much prefer actually sticking my code in the didInsertElement hook as opposed to making it a function and then calling .on('didInsertElement') on the function, but I’ve seen it both ways.