Victor Ferreira
Victor Ferreira

Reputation: 6449

How to send a message from Server to Client in Meteor?

I want to send a message from a Server script in 'server/main.js' to a Cliente script in 'client/main.js'.

I tried a few things with Publish/Subscribe, but i must have done something wrong. The console where the meteor server is running gone crazy with thousands of error messages.

server

Meteor.publish("test", function () {
    this.ready();
    return 'some test';
  });

client

Template.panel.onCreated(function loginOnCreated() {
  Tracker.autorun(function () {
    const handle = Meteor.subscribe('test');
    if(handle.ready()){
      alert('Done')
    }
  });
});

Anyway, I need a server method to call something in client when it's ready.

Reason: Template.panel.onCreated can't query data from Mongodb. It has to wait some seconds. So what I want to do is not possible in Template.panel.onCreated in client. It has to wait until Mongo is ready.

How can I do this?

Upvotes: 1

Views: 1091

Answers (3)

Mukul Jain
Mukul Jain

Reputation: 1175

It has to wait some seconds.

I am assuming data you are retrieving from Mongo is necessary for dom population. For any waiting process you can use loader. You can do this by setting a helper which will be 'false' till you don't get response from server. When you do get that response, populate dom and set this field to true.

Something like:

{{#if dataLoaded}}
  {{domYouWantToPopulate}}
{{else}}
  {{spinner}} //your loading icon template
{{/if}}

Or even if you don't need to data for dom still loading icon for stop user do something till data is received.

So see the thing is, assuming you are in development, you have only client but in real scenario you'll have one server and many clients. So calling client function on every client from server is wrong from both processing and feasibility metrics. Thats why we have APIs to get response from server, so server can send response to only that client which have hit that API.

Upvotes: 1

kkkkkkk
kkkkkkk

Reputation: 7748

You should put Meteor.subscribe outside of Tracker.autorun.

I think the problem is because handle is a reactive data source, so when it changes the function inside Tracker.autorun re-run, it subscribe to server again, a new handle is created and the new handle cause the function to run again. This loops over and over and throw many error messages to your console

Upvotes: 1

Mikkel
Mikkel

Reputation: 7777

You can do it by updating the database and the client helper method alerts it to the fact that the server wanted to say something, or you can use a package like this:

https://atmospherejs.com/raix/eventddp

It allows server initiated messaging. I haven't tried it, but it comes from a good source

Upvotes: 0

Related Questions