AJAX and scoping

how to access a functions arguments or the parent objects properties in an anonymous function? that's the question. for a while handgestrickt cracked their heads about this. we tried several constructs directly with this or with this.options. then we found the solution when we read about closures in Prototype.js. the solution for Prototype.js and Scriptaculous:

var foo = {
    somevar: 'somestring',

    bar: function(somearg) {
        var somevar = this.somevar;
        new Ajax.Request('foo.php',
            {
                method: 'get',
                parameters: { value: 'somevalue' },
                asynchronous: true,
                onSuccess: function() {
                        alert(somevar+' '+somearg);
                }
            }
        );
    }
}

or you directly copy the whole parents object into _this. this is a good idea, if you need a lot of properties of the parent object:

var foo = {
    somevar: 'somestring',

    bar: function(somearg) {
        var _this = this;
        new Ajax.Request('foo.php',
            {
                method: 'get',
                parameters: { value: 'somevalue' },
                asynchronous: true,
                onSuccess: function() {
                        alert(_this.somevar+' '+somearg);
                }
            }
        );
    }
}

the same for Scriptaculous:

var foo = {
    somevar: 'somestring',

    foo: function(element) {
        var somevar = this.somevar;
        new Effect.Opacity(element, {
            from: 0.0,
            to: 1.0,
            beforeStart: function() {
                $(element).style.display = 'block';
                $(element).innerHTML = somevar;
            },
            afterFinish: function() {
                $(element).innerHTML = '';
                $(element).style.display = 'none';
            }
        });
    }
}

Tuesday, 06. March 2007 • trackback url

Add Comment

( to reply to a comment, click the reply link next to the comment )

Comment Title:
Your Name:
Email Address:
Make Public?
Website:
Make Public?

Comment:


Allowed XHTML tags : a, b, i, strong, code, acrynom, blockquote, abbr. Linebreaks will be converted automatically.


Captcha:

captcha image

please type the content of the above image into the following form-field: