.publishDestroy( {id}, [request], [options] )

Purpose

Publish the destruction of a model

Description Accepted Data Types Required ?
1 ID of Destroyed Record int, string Yes
2 Request request object No
3 Additional options object No

publishDestroy() emits a socket message using the model identity as the event name. The message is broadcast to all sockets subscribed to the model instance via the .subscribe model method.

The socket message is an object with the following properties:

  • id - the id attribute of the model instance
  • verb - "destroyed" (a string)
  • previous - an object—if present, contains the attributes and values of the object that was destroyed.

request

If this argument is included then the socket attached to that request will not receive the notification.

options.previous

If this is set, it is expected to be a representation of the model before it was destroyed. This may be used to send out additional notifications to associated records.

Example Usage

UsersController.js

  1. module.exports = {
  2. testSocket: function(req,res){
  3. var nameSent = req.param('name');
  4. if (nameSent && req.isSocket){
  5. User.findOne({name:nameSent}).exec(function findIt(err,foundHim){
  6. User.destroy({id:foundHim.id}).exec(function destroy(err){
  7. User.publishDestroy(foundHim.id);
  8. });
  9. });
  10. } else if (req.isSocket){
  11. User.find({}).exec(function(e,listOfUsers){
  12. User.subscribe(req.socket,listOfUsers);
  13. console.log('User with socket id '+req.socket.id+' is now subscribed to all of the model instances in \'users\'.');
  14. });
  15. } else {
  16. res.view();
  17. }
  18. }
  19. }
  20. // Don't forget to handle your errors

views/users/testSocket.ejs

  1. <script type="text/javascript">
  2. window.onload = function subscribeAndListen(){
  3. // When the document loads, send a request to users.testSocket
  4. // The controller code will subscribe you to all of the 'users' model instances (records)
  5. socket.get('/users/testSocket/');
  6. // Listen for the event called 'message' emited by the publishDestroy() method.
  7. socket.on('message',function(obj){
  8. if (obj.verb == 'destroyed') {
  9. console.log('User '+obj.previous.name+' has been destroyed .');
  10. }
  11. });
  12. };
  13. function destroy(){
  14. // Send the name to the testSocket action on the 'Users' contoller
  15. socket.get('/users/testSocket/',{name:'Walter'});
  16. }
  17. </script>
  18. <div class="addButton" onClick="destroy()">Click Me to destroy user 'Walter' ! </div>

Notes

Any string arguments passed must be the ID of the record.