gpt4 book ai didi

javascript - Mootools JSON : result outside of method/scope

转载 作者:行者123 更新时间:2023-11-29 20:17:59 25 4
gpt4 key购买 nike

var image;
var imgProperties = new Class({
image: new Array(),
json: function() {
var url = protocol + "//" + host + pathname + "/myEchoFile.php";
var jsonRequest = new Request.JSON({
url: url,
onSuccess: function(img) {
this.image[0] = img.name;
this.image[1] = img.width;
this.image[2] = img.height;
alert('img.name=' + this.name); //alerts myImage.jpg
}
}).post();
console.log("this.image[0]=" + this.image[0]); //undefined
//@fixme
//this.image is undefined
}
});

最佳答案

请求不是同步的。 (因此它是 AJAX)它需要时间来触发、完成和设置值。

您应该从 onSuccess 引用您的类实例并调用一个单独的函数,如下所示:

var imgProperties = new Class({

Implements: [Events,Options],

initialize: function(options) {
this.setOptions(options);
},

json: function() {
new Request.JSON({
url: "//" + host + pathname + "/myEchoFile.php",
onSuccess: this.imageLoaded.bind(this)
}).post();
},
imageLoaded: function(data) {
this.image = [data.name, data.width, data.height];
this.fireEvent("imageLoaded", this.image);
}
});

还要注意 onSuccess 函数上的 .bind(this) 确保您指向类实例而不是全局范围(窗口对象?),这是您之前在做什么,修改 window.image

让它像你那样与 anon 一起工作会是这样的:

onSuccess: function(data) {
this.imageLoaded(data);
}.bind(this)

另请注意,我触发了一个名为 imageLoaded 的事件,您可以从实例中使用该事件:

new imgProperties({
onImageLoaded: function(imageArray) {
// access imageArray
// or just access this.image instead!
// or export it to your global namespace like before
window.image = this.image;
// more code that relies on window.image being defined...
}
}).json();

关于javascript - Mootools JSON : result outside of method/scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5549266/

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