Javascript:事件没有调用提交的绑定(..)-回调的副本:-/
Javascript : event is not calling submitted bind(..)-copy of callback :-/
bind() 应该 return 原始函数的副本。但是当将此副本作为回调传递时,原始函数被调用 :-( 已使用 Chrome、Firefox 和 Edge 进行测试. 那么我的推理错误在哪里呢?
<html><body>
<script>
// new api to wrap these nested Cordova callbacks ..
ScanDir = function (sPath, rCallback, iStep){
yes = _Yes.bind(rCallback); // should return a copy/newInstance of _Yes !?!
yes.iStep = iStep;
// simulate a cordova callback ..
document.getElementById("test").addEventListener("click", yes);
}
_Yes = function YES(o){
// this is not the new instance returned by bind(..):
alert(_Yes.iStep); // = undefined
alert(YES.iStep); // = undefined
alert(arguments.callee.iStep); // = undefined
alert(yes.iStep); // wrong, 'yes' must not be global...
}
</script>
<span id="test">click here to trigger callback</span>
<script>
// code that uses my new api..
function Go(v){
if (!v.iStep) return ScanDir(v,Go,1);
alert("continue with switch("+v.iStep+")");
}
Go("Music/");
</script>
</body></html>
最佳解决方案是:
yes = _Yes.bind({callback:rCallback,iStep:iStep});
Inside _Yes 你可以访问:
this.callback();
alert(this.iStep);
不,绑定不会创建新函数,它绑定函数...
bind() 应该 return 原始函数的副本。但是当将此副本作为回调传递时,原始函数被调用 :-( 已使用 Chrome、Firefox 和 Edge 进行测试. 那么我的推理错误在哪里呢?
<html><body>
<script>
// new api to wrap these nested Cordova callbacks ..
ScanDir = function (sPath, rCallback, iStep){
yes = _Yes.bind(rCallback); // should return a copy/newInstance of _Yes !?!
yes.iStep = iStep;
// simulate a cordova callback ..
document.getElementById("test").addEventListener("click", yes);
}
_Yes = function YES(o){
// this is not the new instance returned by bind(..):
alert(_Yes.iStep); // = undefined
alert(YES.iStep); // = undefined
alert(arguments.callee.iStep); // = undefined
alert(yes.iStep); // wrong, 'yes' must not be global...
}
</script>
<span id="test">click here to trigger callback</span>
<script>
// code that uses my new api..
function Go(v){
if (!v.iStep) return ScanDir(v,Go,1);
alert("continue with switch("+v.iStep+")");
}
Go("Music/");
</script>
</body></html>
最佳解决方案是:
yes = _Yes.bind({callback:rCallback,iStep:iStep});
Inside _Yes 你可以访问:
this.callback();
alert(this.iStep);
不,绑定不会创建新函数,它绑定函数...