PDA

View Full Version : each method, scope variables



adube
1 Mar 2012, 6:17 AM
Hi,

In Ext 3.x, I used to be able to do this within a class :



var foo = "bar";
store.each(function(record, index, records) {
alert(foo); // alerts "bar"
}, this);


but in Ext 4 it doesn't seem to work anymore : foo is undefined. I know I could do the following :



var foo = "bar";
store.each(function(record, index, records) {
alert(this.foo); // alerts "bar"
}, {
'me': this,
'foo': foo
});


but I wonder if there's something I'm missing. What would be the correct way to have access to foo within the function given as argument to the each method ?

Many thanks,

Alexandre

mitchellsimoens
1 Mar 2012, 1:39 PM
This is scoping properly for me:


var store = new Ext.data.Store({
fields : ['test'],
data : [
{ test : 'one' }
]
});

store.each(function(rec) {
console.log(this.foo);
}, { foo : 'bar' });

vietits
1 Mar 2012, 5:47 PM
The following code works well for me. I used Ext 4.0.7, Chrome browser.


var store = new Ext.data.Store({
fields : ['test'],
data : [
{ test : 'one' }
]
});


var foo = "bar";
store.each(function(rec) {
console.log(foo); // <- it still displays 'bar' in console.
}, this);

adube
2 Mar 2012, 8:36 AM
You're right. The scope works properly on this small example, but in my application, when I try to do the exact same thing inside a controller class definition, it doesn't work. I'm forced to set my scope elements manually as Mitchell proposed.

I currently don't have a simple test-case showing the issue but trust me, it doesn't work.

Thanks for the reply.

Alexandre