简体   繁体   English

流星:oncreated vs onrendered

[英]Meteor: oncreated vs onrendered

The dilemma: 困境:

  • oncreated: the template is not yet rendered (fires only one time for each template). oncreated:模板尚未渲染(每个模板仅触发一次)。
  • onrendered: the template is rendered (fires multiple times). onrendered:渲染模板(多次触发)。

Is it possible to fire a function only once the template is rendered fully? 是否可以在模板完全渲染后触发函数?

I have a list of messages, that look similar to this 我有一个类似于此的消息列表

<template name="messages">
    <div id="messages">
        <span class="message">{{this.message}}</span>
    </div>
</template>

Each time a new message is inserted into the DOM, I want to know if the text of the message contains the username. 每次将新消息插入DOM时,我想知道消息的文本是否包含用户名。

The following code snippet runs multiple times, of which it should only run a single time. 以下代码段运行多次,其中应该只运行一次。

Template.messages.rendered = function() {

    var username = Meteor.user().services.twitter.screenName;
    $("#messages").bind("DOMSubtreeModified", function() {    
        var lastmessage = $('.message').last().text();
        if (lastmessage.indexOf(username) > -1) {
            //Do something
        }
    }
}

Interchanging rendered by created & changing the template to contain a single message, makes the function run one time for each new message. 通过创建和更改模板呈现的交换包含单个消息,使该函数对每个新消息运行一次。 This means it takes the second to last value for the lastmessage variable: 这意味着它需要lastmessage变量的倒数第二个值:

Template.message.created = function() {
    var username = Meteor.user().services.twitter.screenName;

    var lastmessage = $('.message').last().text();//this is not the last message
    if (lastmessage.indexOf(username) > -1) {
        //Do something
    }
}

Honestly couldn't you do something like this in "rendered". 老实说你不能在“渲染”中做这样的事情。 Or you could put in some callback after you render your extra stuff into the DOM. 或者,在将额外的内容渲染到DOM中之后,您可以进行一些回调。

Additionally you could use self.autorun(() => { if(self.alreadyRun) return; ... }) and self.alreadyRun = new ReactiveVar(false) . 另外你可以使用self.autorun(() => { if(self.alreadyRun) return; ... })self.alreadyRun = new ReactiveVar(false)

Just guessing! 只是猜测!

var self = this;

self.alreadyRun = false;
if(self.alreadyRun){
    self.alreadyRun = true;

    // run once code here

}

通过将代码包装在setTimeout函数中来解决此问题。

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

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