The dilemma:
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
}
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With