Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

callback - How to get Meteor.Call to return value for template?

I've tried to understand this post regarding this concept, however, I'm failing to get it. I have the following simple setup:

/server/test.js
Meteor.methods({ 
  abc: function() {
    var result = {};
    result.foo = "Hello ";
    result.bar = "World!";
    return result;
  }
});

/client/myapp.js
var q = Meteor.call('abc');
console.log(q);

This structure returns to the console undefined.

If I change the myapp.js file to:

Meteor.call('abc', function(err, data) {
  !err ? console.log(data) : console.log(err);
}

I receive the Object in my console.

Ideally this is what I'd like to be able to do, but it doesn't work, stating in the console: Cannot read property 'greeting' of undefined

/client/myapp.js
var q = Meteor.call('abc');

Template.hello.greeting = function() {
   return q.foo;
}

Any help in passing the data from the server object into the template would be greatly appreciated. I'm still learning JavaScript & Meteor.

Thanks!

question from:https://stackoverflow.com/questions/10677491/how-to-get-meteor-call-to-return-value-for-template

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the Meteor.call documentation:

On the client, if you do not pass a callback and you are not inside a stub, call will return undefined, and you will have no way to get the return value of the method. That is because the client doesn't have fibers, so there is not actually any way it can block on the remote execution of a method.

So, you'll want to do it like this:

Meteor.call('abc', function(err, data) {
  if (err)
    console.log(err);

  Session.set('q', data);
});

Template.hello.greeting = function() {
  return Session.get('q').foo;
};

This will reactively update the template once the data is available.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...