繁体   English   中英

如何在Sails.JS中订阅模型实例?

[英]How do I subscribe to a model instance in Sails.JS?

我试图使用这里描述的订阅功能。 但是,在编辑/assets/js/app.js ,我收到此错误:

Uncaught ReferenceError: Room is not defined 

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

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

这是在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`.\n' + 
        'e.g. to send a GET request to Sails, try \n' + 
        '`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中吗?

要订阅模型实例,我使用以下实时模型事件模式,其中一些驻留在客户端上,一些驻留在服务器上。 请记住,客户端不能只订阅itself-你必须向服务器发送一个请求让它知道你被subscribed--这是做安全的唯一途径。 (例如,您可能希望发布包含敏感信息的通知 - 您希望确保连接的套接字有权在订阅它之前查看该信息。)

我将使用具有User模型的应用程序示例。 假设我想在现有用户登录时通知他们。

客户端(第一部分)

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

要将我的套接字请求发送到assets/js/app.js的服务器,我将使用socket.get()方法。 此方法模仿AJAX“get”请求(即$.get() )的功能,但使用套接字而不是HTTP。 (仅供参考:您还可以访问socket.post()socket.put()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()方法将此客户端(套接字)实际订阅到通知。


// 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);
    });
  }

//...

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

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


// 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与自定义控制器操作集成以获取更多信息。

暂无
暂无

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

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