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

How to add event handler to route displayed event in Ember.js?

本文关键字:js Ember 路由 显示 事件 程序 何添加 添加 事件处理      更新时间:2023-09-26

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

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

模板如下:

  <script type="text/x-handlebars" data-template-name="main/sub">
      <a href='image.jpg' class='fancyBox'><img src='image.jpg'></a>
  </script>

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

$("a.fancyBox").fancybox();

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

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

一种可能的方法是创建一个MainSubView并挂接到didInsertElement函数:

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

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

另外值得一提的是,如果在视图从DOM中删除后,对fancybox()的调用需要进行一些清理,那么可以在didInsertElement的对应钩子willDestroyElement中进行清理。

示例:

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

希望能有所帮助。