gpt4 book ai didi

meteor - 在 meteor 中更改DOM后如何调用某些内容?

转载 作者:行者123 更新时间:2023-12-03 21:46:07 25 4
gpt4 key购买 nike

模板.onRendered :

Callbacks added with this method are called once when an instance of Template.myTemplate is rendered into DOM nodes and put into the document for the first time.



DOM改变后有什么方法可以调用吗?

例如, navbar用户打开主页后呈现带有登录/注销按钮的(标题),并且 navbar用户登录后更改(注销按钮)。

我需要在 navbar 之后做点什么已经变了。

最佳答案

您可以通过创建新模板来重构代码,以在子模板上引入更细粒度的生命周期事件。

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());
});

或者,您可以使用 autorunTemplate.navbar.onRendered使用 Tracker.afterFlush 在修改 DOM 后监听用户登录/注销并执行操作.

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

关于meteor - 在 meteor 中更改DOM后如何调用某些内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30010852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com