私はbackbone.jsが新しく、フロントエンドの作業にも若干新しく、ライフサイクルの仕組みをまだあまり理解していません。作成中のBackbone.jsビューのライフサイクル
私たちは基本的にフレームとしてのみ使用するhtmlテンプレートを私たちに提供するDjangoバックエンドを持っています。すべてのロジックは、バックボーン・ビューで処理されます。
私が現在持っている問題は、グラフを描画しようとしていますが、描画関数はレンダリング関数中に存在しないため、IDに基づいてビューを見つけられませんが、私は認識しませんこれを後のフェーズで達成する方法があります。
ページが完全に読み込まれており、それが動作した後、私はクロームコンソールで手動でビューを作成しようとしました:
var main = new MainView();
main.showChart();
ビュー:
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's 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']
});
},
});
それが作成されます:
var chartWidgetView = new WidgetView({'contentView': new ChartView()});
this.initializeWidget(chartWidgetView);
this.$el.append(chartWidgetView.el);
誰かが私に明確でした:
- どうバックボーンは、実際には、ビューの作成を処理しますか?さまざまな段階は何ですか?
- この状況をどのように処理すればよいですか。私のコードのどの時点でhtmlテンプレートの要素が存在するので、グラフ化関数を呼び出すことができますか?
- 私のアーキテクチャは根本的に欠陥がありますか?私はこれを何か全く違うやり方でしようとするべきですか?
ChartViewを作成して親に追加した後、明示的にrender関数を呼び出すことで問題を解決できました: 'chartWidgetView.contentView.render();'。優れた洞察力とリンクをありがとう、私は間違いなく将来のためにこれらを念頭に置くでしょう!私のコードを少しリファクタリングするつもりです;) – jesseniem