【问题标题】:Meteor + Materialize: collapsable in for each doesn't workMeteor + Materialize:每个都不能折叠
【发布时间】:2015-07-02 03:58:20
【问题描述】:

我有一个可折叠(实现),其元素是从 for each 创建的,但是“下拉菜单”不起作用。不在for each 中的所有内容都有效。

我该如何解决这个问题?

jobList.html

<template name="jobList">
<ul class="collapsible" data-collapsible="accordion">
    {{#each jobs}}
        <li>
            <div class="collapsible-header">{{title}}</div>
            <div class="collapsible-body"><p>{{description}}</p></div>
        </li>
    {{/each}}
</ul>

jobList.js

Template.jobList.rendered = function () {
    $('.collapsible').collapsible({
        accordion: false
    });
};

Template.jobList.helpers({
    jobs: function() {
        return Jobs.find();
    }
});

模板jobList 位于另一个模板中,与拥有{{&gt; jobList}} 无关。

【问题讨论】:

    标签: javascript html meteor collapsable materialize


    【解决方案1】:

    这个问题与 DOM 准备有关,在您执行 jQuery 插件初始化时,{{#each}} 循环还没有渲染 HTML 元素。

    解决此问题的方法是定义一个单独的函数来返回要迭代的光标,并在模板的onRendered 回调内的autorun 内观察此光标。

    当我们检测到游标计数被修改时,这意味着一个文档已被添加(特别是当订阅准备好并且初始文档集到达客户端时)或删除,我们必须重新运行jQuery插件初始化。

    在运行 jQuery 初始化之前等待所有其他当前的无效计算完成是很重要的,这就是为什么我们需要使用Tracker.afterFlush(我们无法预测无效计算的重新运行顺序,我们只能此过程完成后执行代码)。

    那是因为返回光标的助手也是一个计算,并且在添加或删除文档时会失效,因此插入或删除相应的 DOM 子集:在 DOM 操作完成后执行我们的 jQuery 插件初始化至关重要.

    function jobsCursor(){
      return Jobs.find();
    }
    
    Template.jobsList.onRendered(function(){
      this.autorun(function(){
        // registers a dependency on the number of documents returned by the cursor
        var jobsCount = jobsCursor().count();
        // this will log 0 at first, then after the jobs publication is ready
        // it will log the total number of documents published
        console.log(jobsCount);
        // initialize the plugin only when Blaze is done with DOM manipulation
        Tracker.afterFlush(function(){
          this.$(".collapsible").collapsible({
            accordion: false
          });
        }.bind(this));
      }.bind(this));
    });
    
    Template.jobsList.helpers({
      jobs:jobsCursor
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      • 2019-09-27
      • 1970-01-01
      • 2013-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多