重新渲染模板不允许我永久更改元素的类?

时间:2014-01-07 04:19:35

标签: meteor

我有一个可排序的列表。

<template name="the_playlist">
        {{#each main_list}}
          <li id="{{index}}" class="list_element">
                 <div class="next_song">...</div>   
                 <div class="destroy">...</div>
                 <div class="element_style">{{song_title}}</div>
          </li>
        {{/each}}
</template>

这是它打印的main_list

Template.the_playlist.main_list = function(){
    //if ret is valid, it will have a songs member
    var ret = Links.find().fetch()[0];
    if (typeof ret == 'undefined'){
        ret = []
    }
    else {
        ret = Links.find().fetch()[0].songs;
    }
    return ret;
}

我正在使用可排序的插件,更重要的是它的update回调,每当用户更改列表或元素添加到列表的位置时,它都会更新。

  $(function() {
    $( "#playlist" ).sortable({
    update: function(){
    Template.list.updateList(); //MODIFIES DB CONTENTS, AND MAIN_LIST's VALUES CHANGE
     }});
    $( "#playlist" ).disableSelection();
  });

* 问题:* 如果页面在加载时已经有列表元素,只有一次,我想添加一个隐藏(.addClass("hide"))每个的类当时页面上的next_song个元素。此*仅在main_list通过调用上面的Template.list.updateList更改*之前有效,之后自动添加的类将消失 - 很可能是由于main_list依赖于db更改而发生的重新呈现。

我使用的JQuery代码片段中的以下内容尝试完成此操作。

$("#playlist li .next_song").each(function(){
   $(this).addClass("hide_song");
})

Here is a demo. Try plugging in the above JQUery code into the console. and then move the list elements around to see the problem.

1 个答案:

答案 0 :(得分:0)

你能不能确定辅助函数是否会出现这种情况?

Template.the_playlist.helpers({
    'list_elements_exist': function() {
        return (!!$('#playlist li').length);
    }
}

然后你可以直接将逻辑插入到模板中:

<div class="next_song{{#if list_elements_exist}} hide_song{{/if}}">...</div>

说实话,我并非100%确定这会根据你的应用程序的结构而具有反应性。如果它不能正常工作,我会引入一个新的会话布尔值list_elements,其值由上面的辅助函数返回。在事件处理程序或created回调中更新其值应该相当容易,以使其跟踪列表中是否有任何项目,这将保证列表呈现为所需,而不管其他依赖项是否发生变化。 / p>

相关问题