How to call something after changing DOM to meteor?

Template.onRendered:

Callbacks added using this method are called once when the Template.myTemplate instance is mapped to DOM nodes and placed into the document for the first time.

Is there a way to call something after changing the DOM?

For example, navbar(title) with the login / logout button is issued after the user opens the home page, and navbarchanges after the user logs in (the logout button).

I need to do something after it has been changed navbar.

+4
source share
1 answer

You can reorganize your code by creating new templates to introduce smaller life cycle events into child templates.

HTML

<template name="navbar">
  <div class="navbar">
    {{#if currentUser}}
      {{> logoutButton}}
    {{else}}
      {{> loginButton}}
    {{/if}}
  </div>
</template>

<template name="loginButton">
  <button class="login">Login</button>
</template>

<template name="logoutButton">
  <button class="logout">Logout</button>
</template>

Js

Template.loginButton.onRendered(function(){
  // will print Login after user logged out
  console.log(this.$("button").text());
});

Template.logoutButton.onRendered(function(){
  // will print Logout after user logged in
  console.log(this.$("button").text());
});

autorun Template.navbar.onRendered / DOM Tracker.afterFlush.

HTML

<template name="navbar">
  <div class="navbar">
    {{#if currentUser}}
      <button class="logout">Logout</button>
    {{else}}
      <button class="login">Login</button>
    {{/if}}
  </div>
</template>

JS

Template.navbar.onRendered(function(){
  // declare a new reactive computation
  // (rerun when the reactive data source is modified)
  this.autorun(function(){
    // listen to the same reactive data source as in the template helper
    // => currentUser
    var user=Meteor.user();
    // this code will run after every other reactive computations depending
    // on the same data source being modified
    Tracker.afterFlush(function(){
      // will print Logout after user logged in
      // will print Login after user logged out
      console.log(this.$("button").text());
    }.bind(this));
  }.bind(this));
});
+1

All Articles