如何在加载模板后立即触发在画布上绘制的操作?

时间:2016-02-13 00:50:25

标签: templates events canvas ember.js

我想在加载模板后立即在模板中绘制画布,所以我认为我需要一个合适的钩子(事件)才能完成它但我找不到它。

我读了How can I trigger an action, when a template is loaded in ember?的答案,我尝试使用“setupController”事件来做,但是没有用。

template.hbs

<canvas id="lyric-editor" width="200" height="200"/>

route.js

import Ember from 'ember';
export default Ember.Route.extend({
  setupController: function() {
    var canvas = document.getElementById('lyric-editor');
    console.log(canvas:" + canvas); 
    // the result is null, it means the template is not loaded at this time.
    var ctx = canvas.getContext('2d');
    ctx.fillStyle = 'white'; // Color of the bars
    ctx.fillRect(50, 50, 40, 40);
  }

在Ember.route类中有beforeModel方法和afterModel方法,所以我期待像 afterTempalteLoad 方法。

任何提示都表示赞赏,提前致谢!

1 个答案:

答案 0 :(得分:3)

我会创建一个组件(使用ember g component canvas-component in the terminal)并在组件中使用didInsertElement钩子。

所以在canvas-component(或你选择调用它的任何东西)

didInsertElement() {
   this._super(...arguments);

   const canvas = this.$();
   console.log(canvas:" + canvas); 
}

我绝对建议您阅读ember docs about components