doremi
doremi

Reputation: 15349

Trouble With JS Closure

I have this js:

(function () {

    Namespace = {

        settings: {
            myVar: 'test' 
        },

        init: function() {

            var memberSearchFrm = document.getElementById('memberSearch');
            memberSearchFrm.onsubmit = function() {

                this.someOtherFunction(); // doesn't work
                console.log(this.settings.myVar); // doesn't work 
            }
         },

        someOtherFunction: function() {
            console.log('test');  
        }
    }

    Namespace.init();
})();

I'm losing the context of 'this' when I go into my onSubmit function. Can you help me understand why this is happening and how to work around this situation?

Upvotes: 1

Views: 161

Answers (3)

Tom Gruner
Tom Gruner

Reputation: 9635

I ran into this same issue with closures and made this fiddle to experiment with different ways to call other functions in a closure.

http://jsfiddle.net/7FzEz/5/

I finally settled with this format:

(function () {

     var obj = {

        settings: {
            myVar: 'test' 
        },

        init: function() {

            var memberSearchFrm = document.getElementById('memberSearch');
            memberSearchFrm.onsubmit = function() {

                obj.someOtherFunction(); 
                console.log(obj.settings.myVar);  
            }
         },

        someOtherFunction: function() {
            console.log('test');  
        }
    }

    obj.init();
})();

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227310

Inside memberSearchFrm.onsubmit, this refers to memberSearchFrm, not to the object you want. You need to save a reference to this.

    init: function() {
        var that = this;
        var memberSearchFrm = document.getElementById('memberSearch');
        memberSearchFrm.onsubmit = function() {
            that.someOtherFunction();
            console.log(that.settings.myVar); 
        }
     },

Upvotes: 3

babsher
babsher

Reputation: 1016

Try the this that trick.

Before you closure set a variable called 'that' to this.

var that = this;

Then use that in you closure. The problem you have having is that the closure is attached to you DOM node and not your object. So when you closure was called this had the value of the DOM node.

Upvotes: 3

Related Questions