Friday, 15 July 2011

node.js - Javascript - How to save a reference to "this" for access in named function callback using prototype pattern -



node.js - Javascript - How to save a reference to "this" for access in named function callback using prototype pattern -

i having problems getting reference javascript object implemented prototype pattern within callback. callback 3rd party component utilize within object. 3rd party object connects message bus.

the next pseudo code shows how started (the real code working)

var mb = require('msgbus') testclass = function() { this.messagebus = new mb.msgbus(); this.messagebus.connect(function(err) { if(err) console.log("error connecting"); else console.log("connected"); }); }

but wanted have automatically retry connecting if callback reports error. cannot set line if if(err) block says "this.messagebus.connection" because have add together anonymous method connect callback , go on , on. so, want split out callback logic named function this

var mb = require('msgbus') testclass = function() { this.messagebus = new mb.msgbus(); this.messagebus.connect(msgbusconnectcallback); } function msgbusconnectcallback(err) { if(err) this???.messagebus.connect(msgbusconnectcallback); else console.log("connected"); }); }

the callback function gets called, cannot figure out how reference object phone call connect again. i've tried create callback prototype function of object, still no reference. cannot create variable in global scope maintain "this" because user of class may create multiple instances of class. new javascript don't know if i'm missing or if need take different approach altogether. appreciate help and/or direction.

this.messagebus.connect.apply(this, [msgbusconnectcallback]);

javascript node.js

No comments:

Post a Comment