Meteor JS: How should I bind events to the window in Meteor?

喜欢而已 提交于 2019-12-23 12:03:42

问题


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?


回答1:


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.




回答2:


This is not the typical Meteor use case, and Meteor doesn't provide any special helpers for such behavior (at least at this moment). So use typical jQuery solution for that. Just make sure that it's wrapped in Meteor.startup().

Meteor.startup(function() {
  $(window).mouseup(function() {...});
});



回答3:


Meteor is almost 1.0 and will be shipping a new ui engine. According to the meteor wiki, the new engine already exposes document body for events.

UI.body.events({
  'mouseup': function () {
    console.log("mouseup");
  }
});

These threads in the google group will help you pinpoint any current problem areas and suggestions on how to solve them.




回答4:


You can use the onRendered and onDestroyed callbacks to register the helper.

var mouseEvent = function (e) {
  console.log(e.clientX, e.clientY);
}

Templates.myTemplate.onRendered(function () {
  $(window).on('mousemove', mouseEvent);
});

Template.myTemplate.onDestroyed(function () {
  $(window).off('mousemove', mouseEvent);
});


来源:https://stackoverflow.com/questions/21486667/meteor-js-how-should-i-bind-events-to-the-window-in-meteor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!