【问题标题】:Meteor - How to know if the data is completely loaded to the templateMeteor - 如何知道数据是否完全加载到模板中
【发布时间】:2014-11-02 15:26:18
【问题描述】:

我正在使用Meteor v0.9.1.1 来填充一个小型即时消息应用程序。 这是我的chat_box 模板:

<ul>
  {{#each messages}}
    <li class="msgLine">
      <strong style="color: {{userTextColor userId}}">
        {{userEmail}}
      </strong>
      {{userMsg}}
      <span>{{createdAt}}</span>
    </li>
  {{/each}}
</ul>

我想要做的是当用户打开这个模板时,最后一条消息行将被聚焦。所以我通过使用:

Template.chat_box.rendered = function(){
  var $chat = $(".chatBox"); // get the div contains the messages list
  $chat.scrollTop($chat.height());
};

但它没有用。通过一步一步的调试,我发现Template.chat_box.rendered函数是在DOM初始化完成后才运行的,而不是在所有消息都从服务器加载完成后

所以问题是,我如何知道所有消息何时已完全加载到模板中,以便之后我可以使$chat.scrollTop($chat.height()); 正确运行。

这就是我通过发布/订阅获取消息列表的方式:

Meteor.subscribe('rooms_by_id', this.params._id);
var currentRoomInfo = Rooms.find().fetch()[0];

if (currentRoomInfo) {
  Meteor.subscribe('messages_by_room', this.params._id);
  var _messages = Messages.find().fetch();

  if (_messages) {
    return {
      roomId: currentRoomInfo._id,
      roomTitle: currentRoomInfo.title.toUpperCase(),
      messages: _messages
    }
  }
}

【问题讨论】:

    标签: templates meteor subscribe


    【解决方案1】:

    您可以使用此处描述的技术: Meteorjs loading message

    但是在你的情况下你应该做一些改进:

    Template.chat_box.rendered = function(){
      Tracker.autorun(function(){
        // every time "chatBoxSubscriptionCompleted" is changed, then closure is rerun
        Session.get("chatBoxSubscriptionCompleted");
    
        var $chat = $(".chatBox"); 
        $chat.scrollTop($chat.height());
      })
    };
    

    onReady 回调传递给Meteor.subscribe

    Meteor.subscribe(
       "chatData",
       param1,param2,
       {
         onReady:function(){
           Session.set("chatBoxSubscriptionCompleted",true)
         },
         onError:function(){}
       }
    )
    

    每当Session.get("chatBoxSubscriptionCompleted") 被更改时,Tracker.autorun 中的闭包就会被执行。

    【讨论】:

    • 这真的是唯一的方法吗?我原以为 Meteor 会有更好的方法,例如var my_data = Meteor.subscribe('my_collection'); if(my_data){ ...数据已加载,所以做点什么...}
    猜你喜欢
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    相关资源
    最近更新 更多