【问题标题】:Template helper crashing app模板助手崩溃应用程序
【发布时间】:2014-08-16 01:31:45
【问题描述】:

在实现这个columnWidth 辅助方法后,我的应用程序正在崩溃我的浏览器。我要做的就是在col-md-7col-md-5(引导类)之间轮换,这样没有两个连续的帖子宽度相同。

columnWidth: function() {
    if (Session.get('columnWidth') === 'col-md-7') {
        Session.set('columnWidth', 'col-md-5');
    } else {
        Session.set('columnWidth', 'col-md-7');
    }

    return Session.get('columnWidth');
}

帖子模板:

{{#each this}}
    <div class="{{columnWidth}}">
        <a href="/a/{{url}}"><img src="{{image}}" height="350" width="{{imageWidth}}" alt=""></a>
        <div class="content">
            <h2><a href="/a/{{url}}">{{title}}</a></h2>
            <p>{{content}}</p>
            <span class="dateAuthored">{{date}}</span>
        </div>
    </div>
{{/each}}

this指的是:

data: function() {
    return Articles.find();
}

任何想法为什么会发生这种情况?我没有收到任何错误。浏览器选项卡只是变得无响应。谢谢。

【问题讨论】:

    标签: meteor spacebars


    【解决方案1】:

    您不断设置相同的反应变量,例如,当调用助手时,第一个 div 会将其设置为 col-md-7,然后当第二行调用它时,您将相同的变量更改为col-md-5 存在问题的原因有两个:

    a) 模板将重绘第一列,因此它们都是 col-md-5

    b) 相同的助手将再次被调用。我相信您的浏览器崩溃是因为您创建了一个无限循环。尝试在您的 columnWidth 帮助器中记录一些内容,看看它被调用了多少次。

    要实现您想要的,您需要获取 {{#each }} 循环的索引,然后让列类取决于它是奇数还是偶数。不幸的是,在流星车把中获取索引有点棘手。

    试试:

    {{#each articles}}
        <div class="{{columnWidth index}}">
            <a href="/a/{{url}}"><img src="{{image}}" height="350" width="{{imageWidth}}" alt=""></a>
            <div class="content">
                <h2><a href="/a/{{url}}">{{title}}</a></h2>
                <p>{{content}}</p>
                <span class="dateAuthored">{{date}}</span>
            </div>
        </div>
    {{/each}}
    

    然后是以下助手:

    articles: function() {
      //'this' in this context should work. 
      //if not just replace with Articles.find().map(...
      var articles = this.map(function(article, index) {
        var i = _.extend(article, {index: index});
        return i;
      });
      return articles;
    },
    columnWidth: function(index) {
      if (index % 2 === 0)
        return "col-md-5";
      else
        return "col-md-7"
    }
    

    【讨论】:

    • 谢谢!很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    相关资源
    最近更新 更多