The amateur programmer
The amateur programmer

Reputation: 1308

Sencha touch 2 ajax callback function scope

I'm having trouble with the program scope when calling Ext.Ajax.request. I need to be able to access the surrounding Ext.data.Model instance from the ajax callback function. What is the proper way to achieve this? I define data model in sencha touch 2 like this:

Ext.define('AlbumsData', {
extend: 'Ext.data.Model',
requires: [
    'Ext.Ajax'
],
config: {
    fields: [
        {name: 'someData',  type: 'string'}
    ]
},
getData: function(){
    Ext.Ajax.request({
        url : '/somedata.json',
        callback: function(options, success, response) {
            //I want to access the surrounding model instance here and "this" certainly doesn't return the instance of the "Ext.data.Model" in which this getData() method is.
        }
    });
}

Upvotes: 1

Views: 1475

Answers (2)

Pawel Furmaniak
Pawel Furmaniak

Reputation: 4806

Use scope option:

getData: function(){
    Ext.Ajax.request({
        url : '/somedata.json',
        callback: function(options, success, response) {
            //I want to access the surrounding model instance here and "this" certainly doesn't return the instance of the "Ext.data.Model" in which this getData() method is.
        },
        scope: this
    });
}

Upvotes: 3

Saffron
Saffron

Reputation: 682

Save your this in a variable before entering the Ext.AJAX context :

getData: function(){
    var scope = this;
    Ext.Ajax.request({
        url : '/somedata.json',
        callback: function(options, success, response) {
            scope.get('someData'); //you can now use scope here
        }
    });
}

Upvotes: 1

Related Questions