如何在 Meteor 中从服务器调用客户端方法? [英] How to invoke a client side method from the server in Meteor?

查看:63
本文介绍了如何在 Meteor 中从服务器调用客户端方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Meteor 方法可以轻松完成相反的操作(从客户端调用服务器端).

The reverse (calling server-side from the client) is easily done with a Meteor Method.

假设您想直接或作为回调从服务器运行客户端方法.例如,用户在您的网站上注册.在服务器上注册成功后,会弹出一个模式窗口,提醒他们注册已成功(我们正在尝试使用单页应用程序的感觉,因此不进行路由器重定向).

Say that you want to run a client-side method from the server, either directly or as a callback. An example could be that a user signs up on your site. After the sign-up on the server is successful, a modal window pops up alerting them that the sign up has been successful (we're trying to go for a single page app feel, so not doing a router re-direct).

以前的搜索似乎说我需要创建一个反应式集合并使用 observe() 监视它,只是为了这个目的:

Previous searches seem to say that I need to create a reactive collection and monitor it with observe() just for this purpose:

调用客户端从服务器获取结果后在 Meteor 中的 js 函数

这看起来有点像hacky.有没有更好的方法来做到这一点?

This seems kind of hacky. Is there a better way to do this?

推荐答案

例如,调用 Accounts.createUser (docs) 是注册用户并在成功或错误时调用回调的好方法.

For your example, invoking Accounts.createUser (docs) on the client would be a fine way to sign up a user and invoke a callback on success or error.

通常,您希望客户端代码以数据为条件,而不是以特定服务器的状态为条件(有一天,您可能有数十台服务器为同一个应用提供服务!).

In general, you want client code to be conditional on data rather than on a particular server's state (you may one day have dozens of servers serving the same app!).

如果您的数据具有一定的真实性(例如 Meteor.userId() 不是 null,因此用户已登录),则在客户端上运行一次代码),您可以使用 stop() 本身的 Deps.autorun (文档).

To run code on the client once if and when your data has a certain truth (e.g. Meteor.userId() is not null, so a user has logged in), you can use a Deps.autorun that stop()s itself (docs).

这篇关于如何在 Meteor 中从服务器调用客户端方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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