gpt4 book ai didi

javascript - this.watch 没有在 deferred.then() 中被调用

转载 作者:行者123 更新时间:2023-11-28 08:59:30 25 4
gpt4 key购买 nike

我遇到了类似于以下 dojo deferred 代码的问题:-

这是XXX.js文件

dojo.declare('XXX', [dijit._Widget, dijit._Templated], {

postCreate: function() {
//getting deferred from somewhere
var _this = this;
deferred.then(function(response) {
console.log("This is getting printed");
_this.watch("value", function(A, B, C) {
console.log("This is not getting printed");
var value = _this.get("value");
_this.onValueChange(value);
});

}

我使用以下代码从其他 JS 文件中调用此类:-

this.object = new XXX({ 
//some args
}
dojo.connect(this.object, "onValueChange", function(value) {
console.log("I am here");
this.onValueChange(value);
});

当我在没有 deferred.then 的情况下使用相同的“watch”时,它工作得很好,但现在当我更改表单中的值时,它不会执行该函数。有什么指点吗?难道是因为当我的“this.object”被创建时,deferred没有执行“then”中的函数?

最佳答案

监视处理程序独立于它们添加的上下文。它们只是挂接到各自的 Stateful 对象上。在上面的代码中,监视 block 的结束大括号 - }) 丢失。也许,这就是问题所在。请引用下面的简单示例:

<script type='text/javascript'>
dojo.require("dijit.form.TextBox");
dojo.require("dojo._base.Deferred");
dojo.require("dojo.ready");

var def = null;

dojo.ready(function(){
def = new dojo._base.Deferred();
var _this = dijit.byId('namefield');
def.then(function(resp) {
_this.watch("value",function(a,b,c) {
console.info(''+a+'-'+b+'-'+c);
});
});
});
function func() {
if(def) {
def.resolve(true);
console.info('resolved');
}
}
</script>
</head>
<body class="claro">
<input type="text" dojoType="dijit.form.TextBox" id="namefield" name="namefield"/>
<button onclick='func()'>click</button>
</body>

因此,即使添加到延迟回调中,监视处理程序也能正常工作。此外,我看到“onValueChange”是从“onValueChange”的事件处理程序中调用的,这是递归的,最终导致堆栈溢出错误。此外,“this”运算符在“dojo.connect”中具有不同的上下文。也请多多关照。

关于javascript - this.watch 没有在 deferred.then() 中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17940621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com