javascript - Passing parameters to a callback function -
javascript - Passing parameters to a callback function -
i'm trying wrap head around javascript callback functions. tried next piece of code:
var callbacktester = function(callback) { var tryme = "are ready, "; callback(tryme); } var createmessagehandler = function(client) { this.client = client; this.result = function(foo){ console.log(foo + " "+ this.client); } }; (new createmessagehandler("john")).result(callbacktester);
instead of "are ready, jason", entire callback function displayed followed name:
function (callback) { var tryme = "are ready, "; callback(tryme); } john
can help me understand how prepare this?
your foo
argument not string, it's callback need call. 1 of possible solutions is:
var callbacktester = function (callback) { var tryme = "are ready, "; callback(tryme); }; var createmessagehandler = function (client) { this.client = client; this.result = function (foo) { foo(function (msg) { console.log(msg + " " + this.client); }.bind(this)); } }; (new createmessagehandler("john")).result(callbacktester);
mind .bind(this)
- need in order preserve this.client
outer scope.
more on bind
function: https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/function/bind
note: don't quite understand purpose of code though. aren't getting callback hell? seek monads/promises instead.
new createmessagehandler
isn't intuitive. imho should either new messagehandler()
or createmessagehandler()
javascript
Comments
Post a Comment