请记住,答案可能非常简单,因为我对 JavaScript 不太熟悉。
我需要从不同的事件调用相同的函数或类来在该过程进行时执行简单的动画。
特别是:当用户单击按钮时,它会触发 AJAX 请求,因此我想通过旋转图像(如旋转器)来动画化此过程。当第一个过程正在进行时,用户可以单击另一个按钮来对另一个元素进行类似的 AJAX 请求,因此第二个旋转器图像假设在第一个过程仍在进行时开始旋转。
我遇到的问题是,一旦我第二次调用同一个类,第一个类就会停止。那是因为我正在更改 Updating.TheID 的 ID,但我认为 Updating 是一个类,每次调用它时都应该启动另一个实例。我刚刚了解到 JavaScript 不是多线程语言,所以我想我可以使用数组或其他东西来单独保存 ID,但我一直在寻找一种使用最少代码的更“优雅”的方法。请指教。
function UpdateData(id) { // This function called when a user clicks a button
Updating.TheID = id;
Updating.Begin();
}
var Updating = {
Degrees: 0,
TheID: 0,
ImageID: '',
Begin: function() {
this.ImageID = "ImgID" + this.TheID;
this.RotateImage();
// CallAJAXProcess(TheID); // This function should run in background
},
RotateImage: function() {
this.Degrees += 15;
document.getElementById(this.ImageID).style.transform = "rotate(" + this.Degrees + "deg)";
if (this.Degrees < 360) {
setTimeout(this.RotateImage.bind(this), 41);
} else {
this.Degrees = 0;
}
}
}
最佳答案
即使您创建一个 new UpdateData()
,这将创建一个唯一的对象,每个对象都将引用同一个 Updating
对象;您没有创建该数据的多个实例。
在这种情况下,您似乎不想在两个更新事件之间共享任何状态。试试这个模式:
function updateData(id) { // This function called when a user clicks a button
var updateOperation = new UpdateOperation(id);
updateOperation.begin();
}
function UpdateOperation(id) {
this.id = id;
this.degrees = 0;
this.imageId = '';
}
UpdateOperation.prototype = {
begin: function() {
this.imageID = "ImgID" + this.id;
this.rotateImage();
// CallAJAXProcess(TheID); // This function should run in background
},
rotateImage: function() {
this.degrees += 15;
document.getElementById(this.imageID).style.transform = "rotate(" + this.degrees + "deg)";
if (this.degrees < 360) {
setTimeout(this.rotateImage.bind(this), 41);
} else {
this.degrees = 0;
}
}
};
关于javascript - 从两个不同的事件调用相同的函数以进行同时处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38296540/