Meteor: oncreated vs onrendered

Dilemma:

  • oncreated: the template is not yet displayed (only one time is triggered for each template).
  • onrendered: the template is rendered (triggered several times).

Is it possible to run the function only after the template is fully displayed?

I have a list of posts similar to this

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

Every time a new message is inserted into the DOM, I want to know if the message text contains a username.

The following code fragment is executed several times, from which it should be run only once.

 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 } } } 

The interaction created by creating and modifying the template to contain one message causes the function to run one time for each new message. This means that for the lastmessage variable, the second value has the last value:

 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 } } 
+6
source share
2 answers

Honestly, you could not do something like this in "rendered". Or you can add some callbacks after you add extra stuff to the DOM.

Alternatively, you can use self.autorun(() => { if(self.alreadyRun) return; ... }) and self.alreadyRun = new ReactiveVar(false) .

Just guess!

 var self = this; self.alreadyRun = false; if(self.alreadyRun){ self.alreadyRun = true; // run once code here } 
+1
source

This is fixed by wrapping the code in the setTimeout function.

-2
source

Source: https://habr.com/ru/post/984278/


All Articles