Skip to content

Commit

Permalink
Merge pull request #4 from franckOL/master
Browse files Browse the repository at this point in the history
Mimics observe() for Node > 4.x (as observe() was deprecated and removed from ES6)
  • Loading branch information
domguinard authored Sep 17, 2016
2 parents 3867cd6 + ec800c0 commit 527fb13
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
12 changes: 11 additions & 1 deletion plugins/corePlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,20 @@ CorePlugin.prototype.showValue = function () {
console.info('Current value for %s is %s', this.model.name, util.inspect(this.model.data[this.model.data.length-1]));
};

/**
* Fake ObjectObserve if not available
*/
var objectObserver = Object.observe || function (resource, callback, extra) {
resource.push = function (data) {
Array.prototype.push.call(resource, data);
callback([{object: resource}]);
};
};

CorePlugin.prototype.observeActions = function () {
var self = this;
_.forEach(self.actions, function (actionId) { //#F
Object.observe(resources.links.actions.resources[actionId].data, function (changes) {
objectObserver(resources.links.actions.resources[actionId].data, function (changes) {
var action = changes[0].object[changes[0].object.length -1];
console.info('[plugin action detected] %s', actionId);
if (self.doAction) self.doAction(action);
Expand Down
16 changes: 14 additions & 2 deletions servers/websockets.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@ var WebSocketServer = require('ws').Server,
resources = require('./../resources/model'),
utils = require('./../utils/utils');

/**
* Fake Array.Observe if not available
*/
var ArrayObserver = Array.observe || function (resource, callback, extra) {
resource.push = function (data) {
Array.prototype.push.call(resource, data);
callback([{object: resource}]);
};
};

exports.listen = function (server) {
var wss = new WebSocketServer({server: server}); //#A
console.info('WebSocket server started...');
Expand All @@ -12,7 +22,7 @@ exports.listen = function (server) {
ws.send(JSON.stringify({'error': 'Invalid access token.'}));
} else {
try {
Array.observe(selectResouce(reqUrl.pathname), function (changes) { //#C
ArrayObserver(selectResource(reqUrl.pathname), function (changes) { //#C
ws.send(JSON.stringify(changes[0].object[changes[0].object.length - 1]), function () {
});
}, ['add'])
Expand All @@ -23,16 +33,18 @@ exports.listen = function (server) {
});
};

function selectResouce(url) { //#E
function selectResource(url) { //#E
var parts = url.split('/');
parts.shift();

var result;
console.log(" parts ==> ", parts)
if (parts[0] === 'actions') {
result = resources.links.actions.resources[parts[1]].data;
} else {
result = resources.links.properties.resources[parts[1]].data;
}
console.log(result);
return result;
}

Expand Down

0 comments on commit 527fb13

Please sign in to comment.