Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call key of object inside of callback?

How can i get variable in handler function of obj? Without reference of the obj in MyClass.

    var obj = {
        func: function(){
            var myClass = new MyClass();
            myClass.handler = this.handler;
            myClass.play();        
        },

        handler: function(){
            //Here i don't have access to obj
            console.log(this); //MyClass
            console.log(this.variable); //undefined
        },

        variable:true
    };

    function MyClass(){
        this.play = function(){
            this.handler();
        };

        this.handler = function(){};
    };

    obj.func();

​ That's construction need you, if you use Base.js or another similar way of oop.

_.bindAll(obj) (underscore metod) also not suitable. It's break overriding in Base.js.

like image 813
Boyo Avatar asked Oct 09 '22 05:10

Boyo


2 Answers

Bind only handler method: http://jsfiddle.net/uZN3e/1/

var obj = {
    variable:true,

    func: function(){
        var myClass = new MyClass();
        // notice Function.bind call here
        // you can use _.bind instead to make it compatible with legacy browsers
        myClass.handler = this.handler.bind(this);
        myClass.play();        
    },

    handler: function(){
        console.log(this.variable);
    }
};

function MyClass(){
    this.play = function(){
        this.handler();
    };

    this.handler = function(){};
};

obj.func();
​
like image 133
Misha Reyzlin Avatar answered Oct 12 '22 20:10

Misha Reyzlin


Use a variable to refer original context:

...
var self = this;
myClass.handler = function(){ self.handler(); };
...
like image 42
Juan Mellado Avatar answered Oct 12 '22 20:10

Juan Mellado