如何在Sails.JS中订阅模型实例? [英] How do I subscribe to a model instance in 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`.\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中吗?
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.)
我将要使用一个具有用户模型的应用程序的示例。假设我想在现有用户登录时通知他们。
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.
在客户端,为简单y,我将使用 / assets / js
文件夹中的现有 app.js
文件(或 / assets / linker / js
文件夹,如果您在构建应用程序时使用 - 链接器
切换。)
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()
方法。此方法模仿AJAXget请求的功能(即 $。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中的
,现在我们实际上可以使用 welcome()
操作结束.js 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
});
// ...
返回服务器端(部分) II)...
最后,我将开始发送消息,服务器端,使用: 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屋!