Ian Atkin
Ian Atkin

Reputation: 6356

JavaScript Object Conundrum

I'm trying to improve my terrible JavaScript skills by using objects rather than just getting by with globals and random sets of functions. My PHP framework until now used two files for any given (set of) page(s)... functions.js and ajax.js. I want to keep the separation, but use objects to achieve the same result.

If I have an object...

var testJS = {

    init: function(options) {
        var defaultSettings = {
            someOption: false,
            fadeLogo: false
        },

        settings = $.extend({}, this.defaultSettings, options),

        base = this;

        // call ajax function...
        ajax.doSomething();

    },

    somethingElse: function() {
        // whatever
    }
});

$(document).ready(function() {
    testJS.init();
});

And then I create an ajax object...

var ajax = {
    doSomething: function(some_var) {
        $.post("Ajax.class.php", {"mode": 'doSomething', 'some_var': some_var}, function(data) {
            something = $.parseJSON(data);
            $('#someId').html(something);

            // call somethingElse function from testJS

        });
    }
}

My question seems really dumb...

How do I call (if I can) the somethingElse function from the ajax object? It seems like it should be available.

Upvotes: 0

Views: 79

Answers (2)

Austin Mullins
Austin Mullins

Reputation: 7427

I think you want to create a new class, not just an object. Then you could build a new testJS object inside your ajax callback.

function testJS() {
        this.init = function(options) {
            var defaultSettings = {
                    someOption: false,
                    fadeLogo: false
            };

            this.settings = $.extend({}, this.defaultSettings, options);

            var base = this;

            // call ajax function...
            ajax.doSomething();

        };

        this.somethingElse = function() {
            // whatever
        };
}

Then, inside the ajax callback:

var myTestJS = new testJS({ /* Your options here */ });
myTestJS.somethingElse();

I like this better than the other answer because, while the constructor for this object is still global, the object itself only exists inside the scope of the callback. If you want the global behavior, you can still use this method. Just call the constructor outside the callback.

Edit

The way I defined the init function above, your base variable isn't going to be able to do anything. I should declare it like this:

function testJS() {
    var base = this;
    ...

And then remove the var base = this; line inside init. Sorry about that.

Upvotes: 1

Guffa
Guffa

Reputation: 700362

As you only have a single instance of the object, you can just use the global variable that contains that instance:

testJS.somethingElse();

Upvotes: 2

Related Questions