Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor: oncreated vs onrendered

The dilemma:

  • oncreated: the template is not yet rendered (fires only one time for each template).
  • onrendered: the template is rendered (fires multiple times).

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.

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:

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
    }
}
like image 285
Fullhdpixel Avatar asked Mar 26 '15 16:03

Fullhdpixel


1 Answers

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.

Additionally you could use self.autorun(() => { if(self.alreadyRun) return; ... }) and self.alreadyRun = new ReactiveVar(false).

Just guessing!

var self = this;

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

    // run once code here

}
like image 80
Ryan Taylor Avatar answered Nov 17 '22 00:11

Ryan Taylor