Reputation: 151
I'm currently learning NodeJS and Javascript OOP. I need to use a package which uses events handler. But I'm a bit confused with the Javascript philosophy.
I've got a node module which runs like this :
var Module = require("...");
//...
MyObject.prototype.start = function() {
var myModule = Module();
myModule.on('connected', function(device) {
console.log('New device connected !');
device.on('status', function(status){
console.log('Device status : '+status);
device.transfer("someStuff");
});
});
}
//...
I would like to call the "transfer()" method of "device" object outside of the "device.on()" events handler. Are there any possibilities ?
Thanks in advance
EDIT : I'm trying this
var Module = require("...");
MyObject.prototype.start = function() {
var myModule = Module();
myModule.on('connected', function(device) {
console.log('New device connected !');
device.on('status', function(status){
console.log('Device status : '+status);
//device.transfer("someStuff");
});
});
}
MyObject.prototype.transferData = function(){
device.transfer("someStuff");
}
Upvotes: 0
Views: 220
Reputation:
Since there are multiple methods of MyObject
that want to access device
, there are a couple of ways you can design this:
MyObject
is instantiated, it promisifies the on('connected')
callback and stores it as, let's say, devicePromise
. All methods on the prototype follow this pattern: return this.devicePromise.then(function (device) { /* do whatever */ })
. Any methods that returned values now return promisesMyObject
cannot be directly instantiated, but can only be created via a factory function that returns a promise of a MyObject
instance. This factory function calls on('connected')
, and resolves the returned promise with a MyObject
instance in which the device
property is set. All methods can access this.device
Upvotes: 1