我有列表,每个单击的项目都会触发不同的API请求。每个请求都有不同的持续时间。成功的话,我会显示一些数据。
问题是,当我单击需要加载约6000的item#1时,紧接在需要加载2000的item#2上之后,我将显示最后单击的项目-这是item#2,因为它具有已经加载,并且一旦item#1接收到数据,我的数据就会更改为该数据。这是错误的,因为我想显示最近点击的数据。
这是我处理事件的方式:
newList.on('click', 'li', (e) => {
let id = $(e.currentTarget).data("id");
store.getCharacterDetails(id).then(docs => {
this.clearDetails();
this.charDetails = docs;
this.displayDetails(this.charDetails);
})
我的API是商店对象的模拟。
我想这可以按预期工作,但是我确实希望最后一个触发的请求有效。
答案 0 :(得分:0)
一种简单粗略的方法可以创建一个数组并推送ID,并且在进行异步操作之后,您只需检查它是否为最新点击即可。但是陷阱是,如果clear
和displayDetails
花费大量时间,并且如果有人在清除和显示它时单击它,则不会注册最新的单击。
无论如何,这是代码,也许您可以用它做得更好。
var latestClick = [];
newList.on('click', 'li', (e) => {
let id = $(e.currentTarget).data("id");
latestClick.push(id);
store.getCharacterDetails(id).then(docs => {
if(id === latestClick[latestClick.length - 1]){
this.clearDetails();
this.charDetails = docs;
this.displayDetails(this.charDetails);
latestClick = [];
}
})
})
答案 1 :(得分:0)
使charDetails
为对象,该对象保留所有结果,并以ID为键。跟踪上次点击的ID。
// in constructor
this.charDetails = {};
this.lastId = null;
newList.on('click', 'li', (e) => {
let id = $(e.currentTarget).data("id");
this.lastId = id;
if (this.charDetails[id] === id) { // don't cancel requests, cache them!
this.displayDetails(this.charDetails[id])
} else {
store.getCharacterDetails(id).then(docs => {
// this runs later, cache the result
this.charDetails[id] = docs;
if (id === lastId) { // only update UI if the id was last clicked
this.displayDetails(docs)
}
});
}
});