Passing scope to callback function / binding

前端 未结 3 1021
梦毁少年i
梦毁少年i 2020-12-23 15:18

I am attempting to pass function scope to a callback method. The problem I am having is that I am getting object scope, which does not provide me with access to the paramet

3条回答
  •  -上瘾入骨i
    2020-12-23 15:59

    The code would work if it was structured like this.

    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
    
        function myHandler(data, ctx) {
            console.log('myHandler():  bar: ' + bar);  // <- prob: bar undefined 
            console.log(JSON.stringify(data));
        }
    
        MySvcWrap.doWork('thang', myHandler, this); // scope object is this
    }
    
    lookup();
    

    The myHandler function can access the local variables of lookup as it is enclosed by it, thus a closure.

    I'd probably try to achieve the same result, by structuring the code like this.

    function myHandler(data, bar, ctx) {
        console.log('myHandler():  bar: ' + bar);  // <- prob: bar undefined 
        console.log(JSON.stringify(data));
    }
    MySvcWrap = {
        doWork: function(p1, callback) {
            var result = {colors: ['red', 'green'], name:'Jones', what: p1};
            if (callback) {
                callback(result);
            } 
        }
    }
    function lookup() {
        var bar = 'food'; // local var
        MySvcWrap.doWork('thang', myHandler.bind(this, bar)); // callback function is bound to the scope
    }
    
    lookup();
    

    Rather than pass the scope, I use bind inside the lookup method. Using bind I can also add the local variables I wish to pass from that scope.

    Of course as bind isn't available in older browsers, you either need to add it via a framework, or use one of the many little snippets of code that add the method if it doesn't exist.

提交回复
热议问题