javascript - Passing scope to callback function / binding -


i attempting pass function scope callback method. problem having getting object scope, not provide me access parameters , local variables in original function. understanding of "this" means current context (whether window or object) in addition to locally declared variables , parameters. [cite richard cornford's excellent work @ http://jibbering.com/faq/notes/closures/ on "execution contexts" section]. understand variables in javascript have function scope (that if declared inside function, accessible within function).

with understanding, in new environment, trying code pattern did alot previous employer, calling asynchronous method, specifying callback handler , passing current scope, expecting available in callback method. not finding case in current environment. (disclosure: using extjs in previous environment... making me feel bit cozy w/ framework, making assumptions going on).

my simple test code demonstrates trying , not work.

function myhandler(data, ctx) {     console.log('myhandler():  bar: ' + bar);  // <- prob: bar undefined      console.log(json.stringify(data)); } mysvcwrap = {     dowork: function(p1, callback, scope) {         var result = {colors: ['red', 'green'], name:'jones', what: p1};         if (callback) {             callback.call(scope||this,result, scope);         }      } } function lookup() {     var bar = 'food'; // local var     mysvcwrap.dowork('thang', myhandler, this); // scope object }  lookup(); 

the problem here 'this' passed mysvcwrap.dowork window global object in case. intention pass function's execution context myhandler.

what have tried. if, instead of 'this', pass object, works, e.g.:

function myhandler(data, ctx) {     console.log('myhandler():  this.bar: ' + this.bar);  // <- no prob: this.bar      console.log(json.stringify(data)); }  function lookup() {     var bar = 'food'; // local var     mysvcwrap.dowork('thang', myhandler, {bar: bar}); // scope object object } 

i need club me on head here... when passing 'this' in first case, of course global scope (i in globally defined function)... problem thought when passing scope had access locally defined variables , parameters w/in context... rocking previous understanding of js?? how accomplish task?

btw, few words scopes in code:

function lookup() {     var bar = 'food'; // local var     mysvcwrap.dowork('thang', myhandler, this); // here points window object , not function scope } 

so same writing:

function lookup() {     var bar = 'food'; // local var     mysvcwrap.dowork('thang', myhandler, window);  } 

it because define lookup function globally. inside dowork function, when write this points mysvcwrap object (because function defined inside object).

if callback function has see bar variable, should defined in same scope,

mysvcwrap = {     dowork: function(p1, callback, scope) {         var result = {colors: ['red', 'green'], name:'jones', what: p1};         if (callback) {             callback.call(scope||this,result, scope);         }      } } function lookup() {     var bar = 'food'; // local var     mysvcwrap.dowork('thang',          function (data, ctx) {             console.log('myhandler():  bar: ' + bar);              console.log(json.stringify(data));         },          this); // scope object }  lookup(); 

in case send anonymous function callback, defined inside lookup function has access local variables; console shows me in cae:

myhandler(): bar: food {"colors":["red","green"],"name":"jones","what":"thang"} 

to make easier support, can define myhandler inside lookup function:

function lookup() {     var bar = 'food'; // local var     var myhandler = function(data, ctx) {         console.log('myhandler():  bar: ' + bar);         console.log(json.stringify(data));     };     mysvcwrap.dowork('thang', myhandler, this); // scope object } 

on other hand, why 1 function should have access local variables of function? maybe can redesigned...

one more way make code working use anonymous function, instead of lookup (will work if declare , execute function once):

(function() {    var bar = 'food';     function myhandler(data, ctx) {        console.log('myhandler():  bar: ' + bar);          console.log(json.stringify(data));     }      mysvcwrap = {        dowork: function(p1, callback, scope) {            var result = {colors: ['red', 'green'], name:'jones', what: p1};            if (callback) {                callback.call(scope||this,result, scope);            }         }     }     mysvcwrap.dowork('thang', myhandler, this);   } )(); 

result same, no lookup function anymore...

and 1 more idea make working... need define callback handler in same scope bar variable defined, can done bit tricky, alternative:

function myhandler(bar) { // in case better call createhandler      return function(data, ctx) {         console.log('myhandler():  bar: ' + bar);          console.log(json.stringify(data));     }  } mysvcwrap = {     dowork: function(p1, callback, scope) {         var result = {colors: ['red', 'green'], name:'jones', what: p1};         if (callback) {             callback.call(scope||this,result, scope);         }      } } function lookup() {     var bar = 'food'; // local var     mysvcwrap.dowork('thang', myhandler(bar), this); // scope object } 

and few resources read javascript scoping , closure:

  1. explaining javascript scope , closures
  2. picking javascript - closures , lexical scoping
  3. javascript: advanced scoping & other puzzles - nice presentation topic

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -