将新的收集项添加到“流星"视图后,如何运行客户端代码? [英] How do I run client-side code after a new collection item has been added to a Meteor view?

查看:87
本文介绍了将新的收集项添加到“流星"视图后,如何运行客户端代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模板中,我调用服务器端方法以将项目添加到集合中.该集合显示在页面上.呈现新项目后,我想将其集中在用户身上.

In my template, I call a server-side method to add an item to a collection. This collection is displayed on the page. Once the new item is rendered, I want to focus it for the user.

这里是触发服务器方法的助手.

Here's the helper that fires the server method.

'click .add-post-button': function(e) {
  var userId = Template.parentData(0)._id;
  Meteor.call('addPost', userId, function(error, result) {
    Session.set('newPostId', result);
  });
}

完成后,将显示新项目.我想把它集中在用户身上.以前,我尝试使用jQuery在上面的回调中执行此操作,但这没有用,因为在执行回调时尚未将其添加到DOM中.现在,我正在尝试使用呈现的回调:

Once this is finished, the new item appears. I want to focus it for the user. Previously, I tried to do it in the callback above with jQuery, but that didn't work because it had not been added to the DOM by the time the callback ran. Now, I'm trying to use the rendered callback:

Template.postsAdmin.rendered = function() {
  var newPostId = Session.get('newPostId');
  if (newPostId) {
    var $newPostCell = $('#' + newPostId);
    $newPostCell.find('.post').focus();
  }
};

不幸的是,这似乎也不起作用.将新项目添加到视图时,此代码不会运行.

Unfortunately, this doesn't seem to be working either. This code does not run when the new item is added to the view.

在将新项目添加到视图中后如何运行代码以使新项目集中?

How can I run code after the new item has been added to the view in order to focus the new item?

推荐答案

您的原始代码确实很接近-您只需要将焦点逻辑放在反应性上下文中,这样它将随着会话变量的更改而再次运行.成功的最短途径是使用模板自动运行:

Your original code is really close - you just need to put the focus logic into a reactive context so it will run again with the session variable changes. The shortest path to success is to use a template autorun:

Template.postsAdmin.onRendered(function() {
  this.autorun(function() {
    var newPostId = Session.get('newPostId');
    if (newPostId) {
      var $newPostCell = $('#' + newPostId);
      return $newPostCell.find('.post').focus();
    }
  });
});


但是,您可能会遇到的一个问题是,您将遇到一种竞赛条件,即在自动运行触发后 会添加新帖子.一个棘手的解决方案是在上面添加一个超时.一种改进的解决方案是将类似于原始代码的内容添加到新添加的post子模板的onRendered回调中:


However, one problem you may run into is that you'll have a race condition where the new post is added after the autorun fires. A hacky solution is to add a timeout to the above. An improved solution is to add something like your original code to the onRendered callback of the newly added post sub-template:

Template.post.onRendered(function() {
  var newPostId = Session.get('newPostId');
  if (newPostId === this.data._id) {
    // add code here to focus this template instance
  }
});

这篇关于将新的收集项添加到“流星"视图后,如何运行客户端代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆