amit
amit

Reputation: 10261

OOP Principles in Javascript

I am having some trouble working with oo javascript. I am creating a new object public and private methods. Now when I am calling the public method, it cannot access the private variable.

I believe I should return the public methods ( the internet ) but dont really know why. Can someone please explain what I am missing?

function something(){
    var somePanel;  // it is a jquery object to a div

    var createWindow = function(data){
        random.xhr('/chat', 'GET', null, function(res){
            var Container = $("#Container");
            somePanel = $("<div/>").addClass('somePanel').append(res);
            Container.append(somePanel.hide());
        });     
    };

    this.activate = function(){
        somePanel.show().siblings().hide();
    };

    this.init = function(data, fn){
        createWindow(data);
    };
};


connections[data] = new something();  // creates a new something object
connections[data].init(data);   //  which creates just a div object, actually
connections[data].activate();  // has code to show this panel and hide every other panel

When I call the activate() method, it cannot find somePanel. What should I be doing differently? And why?

Upvotes: 0

Views: 159

Answers (2)

Jim Schubert
Jim Schubert

Reputation: 20357

you're setting somePanel in the callback to an async call. You can't be guaranteed somePanel is set by the time you call activate().

edit meagar's answer is the best option from an OO perspective. The rest of my answer is aimed at maintaining the readability you're trying to achieve.

You may want to look into using a module that allows for asynchronous chaining (like async) or promises

Upvotes: 0

user229044
user229044

Reputation: 239290

Classic problem with asynchronous methods.

You're xhr handler will not have been invoked when you run activate. You need to wait for your xhr handler to run, and then, in a callback, invoke activate.

Something along these lines:

// ...

this.init = function(data, fn){
    createWindow(data, fn);
};

var createWindow = function(data, fn) {
    random.xhr('/chat', 'GET', null, function(res){
        var Container = $("#Container");
        somePanel = $("<div/>").addClass('somePanel').append(res);
        Container.append(somePanel.hide());
        fn();
    });     
};

// ...

connections[data] = new something();
connections[data].init(data, function () { connections[data].activate() });

Upvotes: 3

Related Questions