简体   繁体   English

在每个循环完成从集合中渲染项目后执行代码

[英]Execute code after each loop finishes rendering items from collection

I am building basic chat application just to try out meteor. 我正在构建基本的聊天应用程序只是为了尝试流星。 When user enters a chat channel, it would be logical to show him the latest messages that are at the bottom. 当用户进入聊天频道时,向他显示底部的最新消息是合乎逻辑的。 Right now I am trying to achieve this with following code 现在,我正在尝试通过以下代码来实现

Template manager 模板管理器

Template.messages.rendered = function(){
  var message_container = this.find('.messages');
  var height = message_container.scrollHeight;
  $(message_container).animate({scrollTop: height}, 1000)
};

Template 模板

<template name="messages">
   <div class="messages">
     {{# each messages}}
   {{> message}}
     {{/each}}
   </div>
</template>

The problem is the code in template manager is being executed, while not all messages have been rendered, thus it results in incorrect height, in var height. 问题是正在执行模板管理器中的代码,而并非所有消息都已呈现,因此会导致高度错误(以var为单位)。

This is similar bottleneck as with microscope demo app from Discover meteor book - the problem with rendered method is that you cannot tell for sure wheter this is fired when template with data finished rendering, or just template rendered before filled with data. 这类似于发现流星书中的显微镜演示应用程序的瓶颈- 渲染方法的问题是,当带有数据的模板完成渲染时,或者仅在填充数据之前渲染的模板,您无法确定是否触发了此操作。 The workaround may be to track message count in some local collection or just variable and in rendered check if current message count is greater that is was before. 解决方法可能是在某些本地集合中跟踪消息计数,或者只是在变量中跟踪消息计数,并在呈现时检查当前消息计数是否大于以前的计数。 If so, scroll a window a bit down. 如果是这样,请向下滚动一个窗口。

This method is used in chaper 14 (if I am not mistaked) of book above. 上面的书的第14章(如果我没记错的话)使用了这种方法。

The simple dirty trick may be to just test a timeout in rendered , but I do not recomment to do so. 一个简单的肮脏技巧可能只是测试render中的超时,但我不建议这样做。

Oh, and one more dirty trick would be to add some invisible element to the end of the dom tree of your page so that all new messages should be inserted before it. 哦,还有另一个肮脏的技巧是在页面的dom树的末尾添加一些不可见的元素,以便所有新消息都应插入到它的前面。 Then just add an event handler on this element position change. 然后,只需在此元素位置更改上添加事件处理程序即可。 Each time a new message is rendered it will push this element a bit down, therefore an event will be triggered. 每次呈现新消息时,都会将该元素向下推一点,因此将触发一个事件。 In that event handler add code to scroll down. 在该事件处理程序中,添加代码以向下滚动。 Similar solution can be found here . 这里可以找到类似的解决方案。

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

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