PDA

View Full Version : Problem using removeListener with a handler called with createDelegate



samax
6 Jul 2009, 2:12 AM
Hello,
I've a problem using the removeListener method on a store field. It simply doesn't work. The handler of the listener is called each time the 'load' event is dispatched, but it should be called only one time.

Here is the adding of the listener:

if (fld_meo.value != null) {
var meo_value = fld_meo.value;
}

if (meo_value) {
fld_meo.store.addListener('load', meoStoreHandler.createDelegate(fld_meo, [meo_value]));
}

I tried these two solutions to remove it:

var meoStoreHandler = function(meo_value) {
this.setValue(meo_value);
this.store.removeListener('load', meoStoreHandler);
}


var meoStoreHandler = function(meo_value) {
this.setValue(meo_value);
this.store.removeListener('load', meoStoreHandler.createDelegate(fld_meo, [meo_value]));
}

But no solution works. Does someone has an idea?
Thanks.

Condor
6 Jul 2009, 2:15 AM
You need to keep a reference to the handler created with createDelegate:

var handler = meoStoreHandler.createDelegate(fld_meo, [meo_value]);
fld_meo.store.on('load', handler);
...
fld_meo.store.un('load', handler);

evant
6 Jul 2009, 2:16 AM
Neither of those refer to the original function, createDelegate will return a new function each time:



function foo(){
}

var a = foo.createDelegate(),
b = foo.createDelegate(),
c = foo.createDelegate,
d = c;

console.log(a == b);
console.log(c == d);

samax
6 Jul 2009, 2:43 AM
Thank you for your replies, but my problem is how can I pass the reference to my reference of function created with the 'createDelegate' method to my handler? The only method is to pass it via itself, but it's not correct, no?

samax
6 Jul 2009, 2:47 AM
Oh, I tried it:

var delegateHandler = meoStoreHandler.createDelegate(fld_meo, [meo_value, delegateHandler]);

if (meo_value) {
fld_meo.store.addListener('load', delegateHandler);
}
with:

var meoStoreHandler = function(meo_value, delegateHandler) {
this.setValue(meo_value);
this.store.removeListener('load', delegateHandler);
}

But it doesn't works (I didn't expect it to work, but I've tried it)...

evant
6 Jul 2009, 2:48 AM
You could keep it on the store:



store.myFn = fn.createDelegate();
store.on('load', store.myFn);
store.un('load', store.myFn);
delete store.myFn;

Condor
6 Jul 2009, 2:50 AM
Why are you not using:

fld_meo.store.on('load', meoStoreHandler.createDelegate(fld_meo, [meo_value]), fld_meo, {single: true});

samax
6 Jul 2009, 4:30 AM
Why are you not using:

fld_meo.store.on('load', meoStoreHandler.createDelegate(fld_meo, [meo_value]), fld_meo, {single: true});
Thank you! I didn't know an option like this existed. It works perfectly :)