I am new to backbone.js and somewhat new to front-end work, and have not yet understood how the life cycle works.
We have a Django backend that provides us with html templates, which we mainly use only as frames. All logic is processed in Backbone modes.
The problem that I currently have is that I am trying to draw a graph, but the graphical display function does not find the representation based on the identifier, since it does not exist during the rendering function, but I do not know how to achieve this at a later stage.
I tried to create the view manually in the Chrome console after the page fully loaded and it works:
var main = new MainView(); main.showChart();
View:
var ChartView = Backbone.View.extend({ title: 'Chart', initialize: function() { // This assures that this refers to this exact view in each function // (except within asynchronous functions such as jquery each) _.bindAll(this); // Saving parameters given by parent this.index = this.options.index; // Retrieve the template from server var template = _.template(getTemplate('chart.html')); // Compile the template with given parameters var compiledTemplate = template({'title': this.title}); // Set the compiled template to this instance el-parameter this.$el.append(compiledTemplate); // Rendering the view this.render(); }, render: function() { var self = this; // Draw the graph when the page is ready $(function(){ self.drawGraph('chart1', this.line1Data); }); // Render function should always return the instance return this; }, drawGraph : function(chartId, lineData) { Morris.Line({ element: chartId, data: [ {y: '2012', a: 100}, {y: '2011', a: 75}, {y: '2010', a: 50}, {y: '2009', a: 75}, {y: '2008', a: 50}, {y: '2007', a: 75}, {y: '2006', a: 100} ], xkey: 'y', ykeys: ['a'], labels: ['Series A'] }); },
});
Where is it created:
var chartWidgetView = new WidgetView({'contentView': new ChartView()}); this.initializeWidget(chartWidgetView); this.$el.append(chartWidgetView.el);
Can anyone clarify to me:
- How does the basic design to create a view work? What are the different stages?
- How should I handle this situation, for example? at what point in my code will there be an element from the html template so that I can call the graphic display function for it?
- Or is my architecture just fundamentally flawed? Should I try to do this in a completely different way?