问题
There is something about reactivity I just don't understand, specifically with lists. My problem can be most easily modeled with the leaderboard example (meteor --create example leaderboard)
First, add this to the client side js (as is done at http://listtest.meteor.com/):
Template.player.rendered = function () {
console.log('Player rendered');
}
...and then watch the console as you run the app. When you switch the selected scientist, you'll notice that each player re-renders, even when it doesn't need to.
Thanks to some help on IRC, I discovered that sub-templating or #isolating the bottom portion of the main template like below (and at http://listtest2.meteor.com/ solves the inefficiency. In other words, when a different player is selected, only two players are now re-rendered: the newly selected and the deselected.
<head>
<title>Leaderboard</title>
</head>
<body>
<div id="outer">
{{> leaderboard}}
</div>
</body>
<template name="leaderboard">
<div class="leaderboard">
{{#each players}}
{{> player}}
{{/each}}
</div>
{{#isolate}}
{{#if selected_name}}
<div class="details">
<div class="name">{{selected_name}}</div>
<input type="button" class="inc" value="Give 5 points" />
</div>
{{/if}}
{{#unless selected_name}}
<div class="none">Click a player to select</div>
{{/unless}}
{{/isolate}}
</template>
<template name="player">
<div class="player {{selected}}">
<span class="name">{{name}}</span>
<span class="score">{{score}}</span>
</div>
</template>
My question is this: why does isolating a different portion of a template cause a different subtemplate's behavior to change?
Thanks so much.
回答1:
Explanation can be found in meteor documenation:
Reactivity isolation
Each template runs as its own reactive computation. When the template accesses a reactive data source, such as by calling Session.get or making a database query, this establishes a data dependency that will cause the whole template to be re-rendered when the data changes. This means that the amount of re-rendering for a particular change is affected by how you've divided your HTML into templates.
Typically, the exact extent of re-rendering is not crucial, but if you want more control, such as for performance reasons, you can use the {{#isolate}}...{{/isolate}} helper. Data dependencies established inside an #isolate block are localized to the block and will not in themselves cause the parent template to be re-rendered. This block helper essentially conveys the reactivity benefits you would get by pulling the content out into a new sub-template.
来源:https://stackoverflow.com/questions/17960366/reactivity-isolation-and-lists