How do I run client-side code after a new collection item has been added to a Meteor view?

后端 未结 2 875
感情败类
感情败类 2021-01-23 13:26

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 u

相关标签:
2条回答
  • 2021-01-23 13:53

    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();
        }
      });
    });
    

    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
      }
    });
    
    0 讨论(0)
  • 2021-01-23 14:01

    One option may be observeChanges? Can you try this?

    in the rendered function do following

    Template.postsAdmin.rendered = function(){
    
       var query = Posts.find({}); //your query
       var handle = query.observeChanges({
           added: function (id, user) {
              //code to set focus???
           }
       });
    }
    

    This code runs whenever there is a new item addeded to minimongo which matches your query.

    Make sure to show the template after you load the data.

    docs link http://docs.meteor.com/#/full/observe_changes

    0 讨论(0)
提交回复
热议问题