我在 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();
现在我需要在显示主/子时调用它。这必须在模板主/子显示后完成。
那么如何给正在显示的模板绑定(bind)事件来调用fancybox呢?
最佳答案
一种可能的方法是创建一个 MainSubView
并挂接到 didInsertElement
功能:
App.MainSubView = Ember.View.extend({
didInsertElement: function() {
$("a.fancyBox").fancybox();
}
});
didInsertElement
将 View 插入 DOM 时将调用该函数。
另外值得一提的是,如果在 View 从 DOM 中删除后对 fancybox()
的调用需要一些清理,您可以在 didInsertElement
's 中执行此操作对应 Hook willDestroyElement
.
例子:
App.MainSubView = Ember.View.extend({
didInsertElement: function() {
$("a.fancyBox").fancybox();
},
willDestroyElement: function() {
// remove here the displayed fancybox
}
});
希望对您有所帮助。
关于javascript - 如何添加事件处理程序以在 Ember.js 中路由显示的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17966345/