开发者

Mootools - how to fix variable scope inside initialize and inside a ajax request

I cant get my for loop to read the maxSlots variable outside of the request. I dont know how or where to declare the variable to make it local to each cla开发者_StackOverflowss but global for the hole class.

//INITIALIZATION
initialize: function(){

    maxSlots = 0;
    var myRequest = new Request({

            url: 'getInventory.php',
            method: 'post',     
            onSuccess: function(responseText){

                maxSlots = responseText;
                console.log(maxSlots);
            },

            onSFailure: function(){
                alert('noo');
            }       

    });
    myRequest.send();

    for (var i = 1; i <= maxSlots; i++){

        var slot = new Element('div', {id: 'slot'+i, class: 'slot'});
        slot.inject(invContainer);
    }


}

EDIT: Ok I tried changing the variable into an option, the alert inside the request = 12 but if i make an alert after the request it says undefined... still the same problem.

//VARIABLES
options: {
    id: '',
    size: '',
    maxSlots: '2'
},

//INITIALIZATION
initialize: function(options){

    this.setOptions(options);
    var myRequest = new Request({

            url: 'getInventory.php',
            method: 'post',     
            onSuccess: function(responseText){

                this.maxSlots = responseText;
                alert(this.maxSlots)
            },

            onSFailure: function(){
                alert('noo');
            }       

    });
    myRequest.send();

            alert(this.maxSlots)
    for (var i = 1; i <= this.maxSlots; i++){

        var slot = new Element('div', {id: 'slot'+i, class: 'slot'});
        slot.inject(invContainer);
    }

}


try this:

   initialize: function(){

        this.maxSlots = 0;
        var myRequest = new Request({

            url: 'getInventory.php',
            method: 'post',     
            onSuccess: function(responseText){

                this.maxSlots = responseText;
                console.log(this.maxSlots);
            }.bind(this),  // <-- always bind the scope in functions

            onSFailure: function(){
                alert('noo');
            }       

    });
    myRequest.send();

    for (var i = 1; i <= this.maxSlots; i++){

        var slot = new Element('div', {id: 'slot'+i, class: 'slot'});
        slot.inject(invContainer);
    }


}

you could also save the variable in the this.options

Good Luck

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜