Meteor JS:如何将事件绑定到Meteor中的窗口? [英] Meteor JS: How should I bind events to the window in Meteor?
问题描述
窗口
似乎不起作用: Template.layout.events({
'mouseup window':function(e){
console.log(mouseup);
}
});
如何将事件绑定到Meteor中的窗口?
下面的代码片段将在创建模板时绑定事件处理程序,并在模板被销毁时解除绑定。应该给你你正在寻找的行为。
var layoutMouseUpHandler = function(e){
console.log ( 'window.mouseup');
};
Template.layout.onCreated(function(){
$(window).on('mouseup',layoutMouseUpHandler);
});
Template.layout.onDestroyed(function(){
$(window).off('mouseup',layoutMouseUpHandler);
});
请注意,事件绑定在 onCreated
处理程序,所以有一个机会,当事件触发时,模板不会被渲染。如果您的处理程序与DOM进行交互,则需要检查。它没有绑定在 onRendered
处理程序中,因为这将导致您的 mouseup
处理程序多次绑定,如果模板是重新渲染。
编辑:正如Serkan在下面提到的,新的UI引擎只调用 onRendered
一旦将模板插入到DOM中。如果您的事件处理程序将与DOM进行交互,这将使它成为比 onCreated
更好的选择。
I am trying to detect a mouseup outside of a window in Meteor. I tried this, but window
doesn't seem to work:
Template.layout.events({
'mouseup window' : function(e) {
console.log("mouseup");
}
});
How should I bind events to the window in Meteor?
The code snippet below will bind the event handler when your template is created and unbind when your template is destroyed. Should give you the behavior you're looking for.
var layoutMouseUpHandler = function(e) {
console.log('window.mouseup');
};
Template.layout.onCreated(function() {
$(window).on('mouseup', layoutMouseUpHandler);
});
Template.layout.onDestroyed(function() {
$(window).off('mouseup', layoutMouseUpHandler);
});
Note that the event is bound in the onCreated
handler, so there's a chance the template will not have been rendered yet when the event fires. If your handler interacts with the DOM, you will need to check for that. It is not bound in the onRendered
handler because that would cause your mouseup
handler to be bound multiple times if the template were re-rendered.
Edit: As Serkan mentions below, the new UI engine only calls onRendered
once when the template is inserted into the DOM. This makes it a better choice than onCreated
if your event handler will interact with the DOM.
这篇关于Meteor JS:如何将事件绑定到Meteor中的窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!