如何订阅 Sails.JS 中的模型实例? [英] How do I subscribe to a model instance in Sails.JS?

查看:21
本文介绍了如何订阅 Sails.JS 中的模型实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 此处描述的订阅功能.但是,在编辑 /assets/js/app.js 时,我收到此错误:

I am attempting to use the subscribe function described here. However, when editing /assets/js/app.js, I am getting this error:

Uncaught ReferenceError: Room is not defined 

所以,我不完全确定为什么,但它找不到我的模型.这是我的代码:

So, I am not entirely sure why, but it cannot find my model. Here is my code:

Room.subscribe(req, [{id: "5278861ab9a0d2cd0e000001"}], function (response) {
  console.log('subscribed?');
  console.log(response);
});

这里是在 app.js 的上下文中

and here is is in the context of app.js

(function (io) {

  // as soon as this file is loaded, connect automatically, 
  var socket = io.connect();
  if (typeof console !== 'undefined') {
    log('Connecting to Sails.js...');
  }

  socket.on('connect', function socketConnected() {

    // Listen for Comet messages from Sails
    socket.on('message', function messageReceived(message) {

      ///////////////////////////////////////////////////////////
      // Replace the following with your own custom logic
      // to run when a new message arrives from the Sails.js
      // server.
      ///////////////////////////////////////////////////////////
      log('New comet message received :: ', message);
      //////////////////////////////////////////////////////

    });


    ///////////////////////////////////////////////////////////
    // Here's where you'll want to add any custom logic for
    // when the browser establishes its socket connection to 
    // the Sails.js server.
    ///////////////////////////////////////////////////////////
    log(
        'Socket is now connected and globally accessible as `socket`.
' + 
        'e.g. to send a GET request to Sails, try 
' + 
        '`socket.get("/", function (response) ' +
        '{ console.log(response); })`'
    );
    ///////////////////////////////////////////////////////////

    // This is the part I added: 
    Room.subscribe(req, [{id: "5278861ab9a0d2cd0e000001"}], function (response) {
      console.log('subscribed?');
      console.log(response);
    });
    //


   });


  // Expose connected `socket` instance globally so that it's easy
  // to experiment with from the browser console while prototyping.
  window.socket = socket;


  // Simple log function to keep the example simple
  function log () {
    if (typeof console !== 'undefined') {
      console.log.apply(console, arguments);
    }
  }


})(

我这样做对吗?我应该将它直接存储在 app.js 中吗?

Am I going about this the right way? should I be storing this directly in app.js?

推荐答案

为了订阅模型实例,我使用了以下 实时模型事件 模式,其中一些驻留在客户端和一些在服务器上.请记住,客户端不能自己订阅——您必须向服务器发送请求,让它知道您喜欢被订阅——这是安全进行订阅的唯一方法.(例如,您可能希望发布包含敏感信息的通知——您希望确保已连接的套接字在订阅该信息之前有权查看该信息.)

To subscribe to a model instance, I use the following Real-Time Model Event pattern, some of which resides on the client and some on the server. Keep in mind the client can’t just subscribe itself- you have to send a request to the server letting it know that you’d like to be subscribed-- this is the only way to do it securely. (e.g. you might want to publish notifications with sensitive information-- you want to make sure a connected socket has permission to see that information before subscribing them to it.)

我将使用一个带有 User 模型的应用程序示例.假设我想在现有用户登录时通知其他人.

I’m going to use an example of an app with a User model. Let’s say I want to notify folks when existing users login.

在客户端,为简单起见,我将使用 /assets/js 文件夹(或 /assets/linker/js 文件夹(如果您在构建应用程序时使用了 --linker 开关.)

On the client-side, for simplicity, I’m going to use the existing app.js file in the /assets/js folder (or /assets/linker/js folder if you used the --linker switch when you built the app.)

要将我的套接字请求发送到 assets/js/app.js 中的服务器,我将使用 socket.get() 方法.此方法模仿 AJAX get"请求(即 $.get() )的功能,但使用套接字而不是 HTTP.(仅供参考:您还可以访问 socket.post()socket.put()socket.delete()).

To send my socket request to the server within assets/js/app.js, I’m going to use the socket.get() method. This method mimics the functionality of an AJAX "get" request (i.e. $.get() ) but uses sockets instead of HTTP. (FYI: You also have access to socket.post(), socket.put(), and socket.delete()).

代码看起来像这样:

 
// Client-side (assets/js/app.js)
// This will run the `welcome()` action in `UserController.js` on the server-side.

//...

socket.on('connect', function socketConnected() {

  console.log("This is from the connect: ", this.socket.sessionid);

  socket.get(‘/user/welcome’, function gotResponse () {
    // we don’t really care about the response
  });

//...

服务器端(第一部分)

UserController.js 中的 welcome() 操作中,现在我们实际上可以使用User.subcribe() 方法.

Server-Side (Part I)

Over in the welcome() action in UserController.js, now we can actually subscribe this client (socket) to notifications using the User.subcribe() method.

 
// api/UserController.js

//...
  welcome: function (req, res) {
    // Get all of the users
    User.find().exec(function (err, users) {
      // Subscribe the requesting socket (e.g. req.socket) to all users (e.g. users)
      User.subscribe(req.socket, users);
    });
  }

//...

回到客户端(第二部分)...

我希望套接字监听"我将从服务器发送的消息.为此,我将使用:

Back on the client-side (Part II)...

I want the socket to ‘listen’ for messages I’m going to send it from the server. To do this I’ll use:

 
// Client-side (assets/js/app.js)
// This will run the `welcome()` action in `UserController.js` on the backend.

//...

socket.on('connect', function socketConnected() {

  console.log("This is from the connect: ", this.socket.sessionid);

  socket.on('message', function notificationReceivedFromServer ( message ) {
    // e.g. message ===
    // {
    //   data: { name: ‘Roger Rabbit’},
    //   id: 13,
    //   verb: ‘update’
    // }
  });

  socket.get(‘/user/welcome’, function gotResponse () {
    // we don’t really care about the response
  });

// ...

回到服务器端(第二部分)...

最后,我将开始在服务器端发送消息:User.publishUpdate(id);

 
// api/SessionController.js

//...
  // User session is created
  create: function(req, res, next) {

    User.findOneByEmail(req.param('email'), function foundUser(err, user) {
      if (err) return next(err);

      // Authenticate the user using the existing encrypted password...
      // If authenticated log the user in...

      // Inform subscribed sockets that this user logged in
      User.publishUpdate(user.id, {
        loggedIn: true,
        id: user.id,
        name: user.name,
        action: ' has logged in.'
      });
    });
  }
//...

您也可以查看构建 Sails 应用程序:Ep21 - 使用实时模型事件将 socket.io 和 Sails 与自定义控制器操作集成 了解更多信息.

You can also check out Building a Sails Application: Ep21 - Integrating socket.io and sails with custom controller actions using Real Time Model Events for more information.

这篇关于如何订阅 Sails.JS 中的模型实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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