【问题标题】:Render router's template to dynamic point in DOM将路由器的模板渲染到 DOM 中的动态点
【发布时间】:2015-06-03 05:16:58
【问题描述】:

我想在点击元素后立即将显示模板渲染为索引模板。

一些代码(玉):

template(name="index")
  ul
   for post in posts
     li
      a(href="posts/1")= post.title
      // render full post #1 here if link clicked
     li
      a(href="posts/2")= post.title
      // render full post #2 here if link clicked
     li
      a(href="posts/3")= post.title
      // render full post #3 here if link clicked

所以当用户点击显示帖子链接时,我不需要替换整个索引模板。我只需要在链接到这篇文章后立即渲染显示模板。

另外我需要同时显示一个帖子,所以如果用户点击一个帖子,然后另一个帖子,第一个应该从 DOM 中删除,第二个应该在他的位置呈现(在显示链接之后)。

如何使用流星和 Iron Router 做到这一点?

【问题讨论】:

    标签: meteor iron-router


    【解决方案1】:

    执行此操作的一种方法是继续渲染所有内容,但将其隐藏。然后,您可以添加一个单击事件处理程序,该处理程序隐藏所有内容并仅显示被单击的内容:

    <template name='index'>
      <ul>
        {{#each posts}}
          <li>
            <a href='#' class='show-index-link' _id="{{_id}}"><!--Store _id so we can retrieve it in event handler-->
            <div class='post-show-hide' id='post-show-hide-{{_id}}' style='display: none;'><!-- make it easy to select in the event handler-->
              {{> post}}<!-- data context is the post in question -->
            </div>
          </li>
        {{/each}}
      </ul>
    </template>
    

    那么您的事件处理程序可能如下所示:

    Template.index.events({
      'click .show-index-link': function(event) {
        var _id = $(event.currentTarget).attr('_id'); // grab the ID of the post to show
        event.preventDefault();
    
        $('.post-show-hide').hide(); // hide all of them
        $('#post-show-hide-' + _id).show(); // Show only the one we just clicked on
      }
    });
    

    对我来说,这似乎是实现此目的最直接的方法,但如果您担心将所有帖子发送到客户端的性能,您也可以考虑使用一个订阅相关帖子的事件处理程序。这似乎要困难得多(如果你真的担心那种性能问题,你可以更容易地解决它,例如分页),所以除非你真的需要它,否则我会坚持一些简单的事情,比如上面的解决方案。

    【讨论】:

      【解决方案2】:

      Blaze.renderBlaze.renderWithData

      在您的标记中插入占位符:

      template(name="index")
        ul
         for post in posts
           li
             a(href="posts/1")= post.title
             div(id="post1") // render full post #1 here if link clicked
           li
             a(href="posts/2")= post.title
             div(id="post2") // render full post #2 here if link clicked
           li
             a(href="posts/3")= post.title
             div(id="post3") // render full post #3 here if link clicked
      

      然后设置你的助手:

      Template.index.helpers({
        'click a': function(ev){
          ... determine which link was clicked on
          ... pick the node to inject ex:
          var node = $('#post2');
          Blaze.render('postTemplate',node);
        }
      });
      

      【讨论】:

      • 酷!正是我需要的!谢谢你:)
      猜你喜欢
      • 2014-12-14
      • 1970-01-01
      • 2015-12-24
      • 2015-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-24
      • 1970-01-01
      相关资源
      最近更新 更多