문제

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