简体   繁体   English

如何从流星js中的另一个客户端触发客户端事件

[英]How to trigger a client event from another client in meteor js

I have one client app for a tablet and one for a notebook.我有一个用于平板电脑的客户端应用程序和一个用于笔记本电脑的客户端应用程序。 Those apps are located in the client folder: "tablet" and "monitor" respectively.这些应用程序位于客户端文件夹中:分别是“平板电脑”和“显示器”。 My question is, is it possible to trigger an event from the tablet app to the notebook app?我的问题是,是否可以触发从平板电脑应用到笔记本应用的事件? Because I want to switch through a pagination synchronously.因为我想同步切换一个分页。

The typical pattern for this in Meteor would be to save or update a document in a collection that is subscribed to by both clients and then have the clients react to that new or updated value. Meteor 中的典型模式是保存或更新两个客户端都订阅的集合中的文档,然后让客户端对新的或更新的值做出反应。

For example:例如:

lib:库:

SharedState = new Mongo.Collection('sharedstate');

server:服务器:

Meteor.publish('shared',function(){
  return SharedState.find({ userId: this.userId });
});

client:客户:

Meteor.subscribe('shared');

in your client that is creating the event:在创建事件的客户端中:

SharedState.upsert(
  { userId: Meteor.userId() },
  { userId: Meteor.userId(), state: "foo" }
);

Then in your client that is looking for the event use a Tracker.autorun (or alternatively, observeChanges ) to see that the shared state has changed:然后在您正在查找事件的客户端中,使用Tracker.autorun (或者, observeChanges )来查看共享状态是否已更改:

Tracker.autorun(function(){
  let state = SharedState.findOne({ userId: Meteor.userId() });
  if ( state === "foo" ){
    ... do your thing
  }
});

Here I'm assuming that your app running on your tablet and notebook are being used by the same user - hence the key for the shared state is the userId .在这里,我假设您在平板电脑和笔记本电脑上运行的应用程序由同一用户使用- 因此共享状态的关键是userId If OTOH you were sharing state across a classroom (one teacher, several students), then you might use something like classroomId instead.如果 OTOH 您在一个教室(一位老师,几位学生)中共享状态,那么您可能会使用诸如classroomId东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM