最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Meteor.js: How to set a div height dynamically via Javascript - Stack Overflow

programmeradmin7浏览0评论

I'm using templates/handlebars but none of the event handlers are triggered when the browser window resizes. Not sure how to capture the resize event in order to dynamically set the div's height to be within the viewport

Here's a sample of what I've tried so far using meteor's event map:

Template.basic.events({
    'resize window' : function(evt, tmpl){
         alert("test");
     },
};

Ideally this handler would be called each time the window is resized so I can use $(window).height() to set the div's height in the html using tmpl.find('#main-div');.

I'm using templates/handlebars but none of the event handlers are triggered when the browser window resizes. Not sure how to capture the resize event in order to dynamically set the div's height to be within the viewport

Here's a sample of what I've tried so far using meteor's event map:

Template.basic.events({
    'resize window' : function(evt, tmpl){
         alert("test");
     },
};

Ideally this handler would be called each time the window is resized so I can use $(window).height() to set the div's height in the html using tmpl.find('#main-div');.

Share Improve this question edited May 18, 2020 at 9:40 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Nov 12, 2013 at 3:38 user2981638user2981638 331 silver badge4 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 9

Most problems which directly rely on jQuery can be solved using the onRendered callback like so:

Template.basic.onRendered(function() {
  $(window).resize(function() {
    console.log($(window).height());
  });
});

Technically this works, but because window never gets removed as part of the rendering process, this technique has a big disadvantage: it adds a new resize handler every time the template is rendered.

Because window is always available, you can instead use the created and destroyed callbacks to register and unregister the handlers:

Template.basic.onCreated(function() {
  $(window).resize(function() {
    console.log($(window).height());
  });
});

Template.basic.onDestroyed(function() {
  $(window).off('resize');
});

Note, however, that stopping the resize handler in onDestroyed may not really be what you want. See this question for more details.

Also note that in the current version of meteor, you can check the number of event handlers like so:

$._data($(window).get(0), "events").resize.length
发布评论

评论列表(0)

  1. 暂无评论