如何添加事件处理程序来路由Ember.js中显示的事件?

Tom*_*ski 1 javascript jquery fancybox ember.js

我在Ember.js中有一个简单的网站,它有:

App.Router.map(function() {
  this.resource('main', { path: '/main' });
    this.route('sub', { path: '/sub' });
Run Code Online (Sandbox Code Playgroud)

和模板这样:

  <script type="text/x-handlebars" data-template-name="main/sub">
      <a href='image.jpg' class='fancyBox'><img src='image.jpg'></a>
  </script>
Run Code Online (Sandbox Code Playgroud)

现在为了制作FancyBox,当我点击它在新图层中打开的图像时我通常会调用函数:

$("a.fancyBox").fancybox();
Run Code Online (Sandbox Code Playgroud)

现在我需要在显示main/sub时调用它.这必须在显示模板main/sub后完成.

那么如何将事件绑定到正在显示的模板以调用fancybox?

int*_*xel 6

一种可能的方法是通过创建一个MainSubView和挂钩didInsertElement函数:

App.MainSubView = Ember.View.extend({
  didInsertElement: function() {
    $("a.fancyBox").fancybox();
  }
});
Run Code Online (Sandbox Code Playgroud)

didInsertElement将视图插入DOM时,将调用该函数.

另外值得一提的是,如果要调用fancybox()视图是从DOM中移除后需要一些清理了你会怎么做这didInsertElement对口挂钩willDestroyElement.

例:

App.MainSubView = Ember.View.extend({
  didInsertElement: function() {
    $("a.fancyBox").fancybox();
  },
  willDestroyElement: function() {
    // remove here the displayed fancybox
  }
});
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.