Вопрос

In my backbone+marionette application I have used morris.js Line Chart. This chart takes an array of data from the model. And must be created after DOM creating (DOM dependent).

Сode to create the chart:

_createChartData: function () {
    var trends = this.model.get("trends"),
        chartData = [];

    $.each(trends, function (x, y) {
        // some actions with data
    });

    return chartData;
},
_createChart: function () {      
    Morris.Line({
        element: 'promo-chart',
        data: this._createChartData(),
        xkey: 'date',
        ykeys: ['y', 'g'],
    });
}

View and Controller:

define(['utils/hbs', 'modules/model/promo-mdl'], function( Hbs, Promo){
    var PromoView = Marionette.ItemView.extend({
        initialize: function () {
            this._events();
        },

        template: Hbs.tf('modules/promo'),

        templateHelpers: {
            // handlebars helpers
        },

        events: {
            'click #submitBtn'          : '_savePromo',
        },

        _events: function () {
            this.listenTo(this.model, 'change', this.render);
        },

        _savePromo: function () {
            // save data
        }        
    });

    return Marionette.Controller.extend({
        initialize: function (config) {
            this.region = config.region;
            this.model = new Promo({});
            this.model.fetch();
            this._events();
        },

        _events: function () {
            App.vent.on('show:promo', this._show, this);
        },

        _show: function () {
            this.view = new PromoView({ model: this.model });
            this.region.show(this.view);
        }
    });
});

I tried to create this chart in View, but got an errors - empty data or no chart element in DOM. Where to create this chart, in View or Controller? And which event to use? initialize, onShow or onRender?

Это было полезно?

Решение

It seems like you're creating the chart when the element it uses isn't in the DOM yet. Try creating the chart in the view's onShow function:

var PromoView = Marionette.ItemView.extend({

    // code...

    onShow: function(){
      // create chart here
    }
});

Другие советы

onDomRefresh function in the view could be what you are looking for.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top