views:

38

answers:

1

I have a setup where I get some information, in an ajax call, then I immediately use some of that information for another call, and then I populate some fields.

The problem is that I am not certain how to create the anonymous function so that it can call this.plantName.

Right now the value of this.plantName is undefined.

I know that there are missing close braces, but I am not going to try to line them up as that will cause confusion, so please ignore the missing close braces.

TabLinks.prototype.plantName = '';

TabLinks.prototype.init = function() {
    this.updateTab('PlantDropDown', 'retrievePlants', 'retrieveAllPlants', 'tab3', function() { return this.plantName; });
};

function TabLinks() {
    this.updateTab = function(entityname, wsbyid, webservicename, parentContainer, defaultValue) {
        $("#" + parentContainer + "link").bind('click', function() {
            $.ajax({
                type: "POST",
...
                success: function(result) {
                    myData = JSON.parse(result.d);
                    $.ajax({
                        type: "POST",
...
                        success: function(result2) {
...
                                    myelem.value = JHEUtilities.testIsValidObject(defaultValue) ?
                                    defaultValue() :
                                    '';

Update: Here is the solution that worked, I didn't realize the two returns of functions:

this.updateTab('PlantDropDown', 'retrievePlants', 'retrieveAllPlants', 'tab3',
function() {
    var app = this;
    return function() {
        return function() {
            return app.plantName;
        }
    }()
}
);

So I had to call it thusly: defaultValue()();

A: 

The way I program my way out of this is to make sure that the closure is returned from a function in the scope of the captured variables. Something like so:

function foo(){
    var myFoo = 1;
    return function (){return function() { myFoo += 1; return myFoo }}()
} //                                                                  ^^
TokenMacGuy
Thank you, I will try that. So would I pass in the 'this' variable to this closure?
James Black