Reputation: 15508
The referenced fiddle and code here does not actually work. I don't know how to get a controller defined in a one file project. At any rate, my issue is that when I'm in a controller function (afterrender in my case). I can't figure out how to get a reference to testval. if I create a simple example with just lines 19-32 in a separate launch it works (see fiddle: https://fiddle.sencha.com/#fiddle/1ae7 ).
However, in my controller case I'm not getting the testval in my success or failure event. how to pass in context (scope) of my function I'm calling the ajax request from?
https://fiddle.sencha.com/#fiddle/1ae9
Ext.define('mycontroller', {
extend: 'Ext.app.Controller',
alias: 'controller.main',
myfun: function() {
console.log('controller:myfun');
}
});
var mypanel = Ext.create('Ext.panel.Panel', {
controller: {
type: 'main'
},
listeners: {
afterrender: function() {
console.log('afterrender');
var testval = "hi there";
Ext.Ajax.request({
method: 'POST',
url: '/dummy',
jsonData: 'jsonData',
scope: this,
success: function() {
// this never gets called, just testing scope
},
failure: function() {
// testval IS NOT IN SCOPE, CONFUSED ABOUT SCOPE AND THIS HERE
Ext.Msg.alert('info', testval);
}
});
}
},
html: 'test panel'
});
Ext.application({
name: 'Fiddle',
launch: function() {
Ext.create('Ext.container.Viewport', {
layout: 'fit',
items: [mypanel]
});
}
});
Upvotes: 0
Views: 1975
Reputation: 20244
You have to think in basic JS structures to find the scope. The basic structure is a function Ext.Ajax.request()
, which takes one(!) parameter in this case.
That single parameter is an object. If you are using this
inside an object, this
refers to that very object. The pattern used by Sencha to transfer the outer scope into the function would be
var me = this;
Ext.Ajax.request({
...
scope: me,
...
});
That said, var testvar
is a local variable, which is not scoped into any object - it is scoped to the function block.
var testval = "hi there";
Ext.Ajax.request({
failure: function() {
// testval IS ALWAYS "IN SCOPE" HERE, NO MATTER WHAT YOU SET scope TO,
// BECAUSE IT IS DEFINED INSIDE THE SAME FUNCTION BLOCK
Ext.Msg.alert('info', testval);
}
});
That said, I have made a working fiddle for you by just fixing the error I found in browser console.
Upvotes: 3