简体   繁体   English

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

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

I have a simple site in Ember.js that has this: 我在Ember.js中有一个简单的网站,它具有以下功能:

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

And template like this: 和这样的模板:

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

Now in order to make FancyBox so that when i click on the image it opens in new layer i normally call function: 现在为了制作FancyBox,以便当我单击图像时它在新层中打开,我通常调用函数:

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

Now i need to call it when main/sub is displayed. 现在我需要在显示主/子时调用它。 And this must be done after the template main/sub is displayed. 并且必须在显示模板主/子之后完成。

So how to bind event to template being displayed in order to call fancybox? 那么如何将事件绑定到要显示的模板以便调用fancybox?

One possible way to do it would be by creating a MainSubView and hook into the didInsertElement function: 一种可能的方法是创建MainSubView并连接到didInsertElement函数:

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

The didInsertElement function will be called when the view was inserted into the DOM. 将视图插入DOM时,将调用didInsertElement函数。

Also worth mentioning is that if the call to fancybox() needs some clearing up after the view was removed from the DOM you would do this in didInsertElement 's counterpart hook willDestroyElement . 还值得一提的是,如果从DOM中删除视图后,对fancybox()的调用需要进行一些清理,则可以在didInsertElement对应钩子willDestroyElement

Example: 例:

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

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM