Poyi
Poyi

Reputation: 930

Meteor update collection doesn't refresh on client

I have a collection which has style properties which I iterate through and apply to the corresponding element:

// server side
Meteor.publish('elements', function(){
  return Elements.find();
});

//client side
Meteor.subscribe("elements");

setupElements = function () {
    var currentUserId = Meteor.userId();
    var elements = Elements.find({user: currentUserId}).fetch();
    elements.forEach(function(e){
    var elementId = e._id;
    eval("document.getElementById('" + elementId + "').removeAttribute(\"style\")");
    var width = e.width;
      for (var i in width) {
        eval("document.getElementById('" + elementId + "').style.width"= \"" + width[i] + "\"");
      }
    });
}

Template.element.rendered = function() {
  if(!this._rendered) {
    this._rendered = true;

    // iterate through element and apply width style to each
    setupElements();
  }
}

// template
<template name="element">
  {{#each element}}
    <div id="{{_id}}" class="element">{{text}}</div>
  {{/each}}
  <button id="change-style">Change style</button>
</template>

The template renders and applies the corresponding width to each element. However, when I trigger an update like below:

'click #change-style': function() {
    Meteor.call('updateElements'); // assume server-method successfully updated all elements
    setupElements(); // thought this will fetch new style and re-apply
  },

The documents are updated in the database but the template/view does not react to the change until I refresh the page or trigger the event again. Seems like the database is not refreshed on the client-side when the server updates it. Wondering what's the right setup to make the re-apply style reactive, or if there is a way to force refresh template.

Thanks in advance!

Upvotes: 0

Views: 1176

Answers (1)

Tarang
Tarang

Reputation: 75975

While there are probably better ways to do what you're doing by using standard reactive html & JQuery. In the context of your exact question:

Javascript is asynchronous. The setupElements fires before the results arrive from the server. Simply fire it in the .call callback:

Meteor.call('updateElements', setupElements);

Upvotes: 2

Related Questions