[請益] 前端async的問題

看板Soft_Job作者 (500年沒換暱稱了)時間5年前 (2018/08/23 17:48), 編輯推噓12(12013)
留言25則, 17人參與, 5年前最新討論串1/1
想請教前端的大大這個應該是很基本的問題 一開始在頁面上列出很多個items,每個item會有一個加入的按鈕 點了加入之後,就會透過ajax去call api在後端db紀錄下來 到這邊都沒什麼問題 但是想在前端把剛剛item的加入按鈕變成不能點,文字也變成已加入 code snippet像這樣 $('.btn-add-favorite').click(function(event) { axios.post('/favorite/add', { itemId: $(this).data("item-id") }) .then(function (response) { // handle success $(this).attr('disabled', true); $(this).html('已加入'); }) .catch(function (error) { // handle error }); }); 不過顯然在success那邊用this不會是同樣的node 通常這種應用要怎麼找到原本的node呢? 目前想到的作法,就是每個item塞一個unique id 進到click後把id用變數存下來 success那邊再用dom把這個id找出來處理 不知道比較好的作法是什麼呢? P.S. 我在ptt或facebook上找不太到適合討論這類問題的板,有推薦的討論區嗎... 這個問題keyword不知道要下什麼, stack overflow上不知道怎麼找 T_T -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.140.253.26 ※ 文章網址: https://www.ptt.cc/bbs/Soft_Job/M.1535017694.A.3C1.html

08/23 17:50, 5年前 , 1F
在 function(event){} 開頭寫個 var that = this,然後
08/23 17:50, 1F

08/23 17:50, 5年前 , 2F
後面都用 that
08/23 17:50, 2F

08/23 18:14, 5年前 , 3F
關鍵字是this, binding, scope, javascript
08/23 18:14, 3F

08/23 18:27, 5年前 , 4F
其實有ajax版XD
08/23 18:27, 4F

08/23 18:44, 5年前 , 5F
好ES6不用嗎
08/23 18:44, 5F

08/23 18:54, 5年前 , 6F
在success那裡的 function(response){} 改成(res)=>{}
08/23 18:54, 6F

08/23 18:55, 5年前 , 7F
使用ES6的Arror Function 就能避開this的問題
08/23 18:55, 7F

08/23 19:35, 5年前 , 8F
有 Web版
08/23 19:35, 8F

08/23 20:10, 5年前 , 9F
臉書有 JavaScript.tw 社團喔
08/23 20:10, 9F

08/23 22:37, 5年前 , 10F
全部改成await
08/23 22:37, 10F

08/23 23:01, 5年前 , 11F
臉書也有Frontend Developers Taiwan喔
08/23 23:01, 11F

08/24 00:58, 5年前 , 12F
Function.prototype.bind
08/24 00:58, 12F

08/24 01:08, 5年前 , 13F
想回答的都被講完了 看來強者都在這板
08/24 01:08, 13F

08/24 09:37, 5年前 , 14F
高手如雲
08/24 09:37, 14F

08/24 10:39, 5年前 , 15F
感謝高手大大們~ PTT的ajax跟web_design板看起來冷清
08/24 10:39, 15F

08/24 10:39, 5年前 , 16F
這裡的討論比較熱烈而且很有深度!
08/24 10:39, 16F

08/24 13:23, 5年前 , 17F
這是this bind的問題 因為axios的callback在執行的時
08/24 13:23, 17F

08/24 13:23, 5年前 , 18F
候this會指向window 在callback的後面加上.bind(this)
08/24 13:23, 18F

08/24 13:23, 5年前 , 19F
就可以綁定onclick的this了
08/24 13:23, 19F

08/24 13:25, 5年前 , 20F
推薦去看這篇文章 介紹的很詳細 https://ithelp.ithom
08/24 13:25, 20F

08/24 13:25, 5年前 , 21F
e.com.tw/m/articles/10193193
08/24 13:25, 21F

08/27 08:58, 5年前 , 22F
ES6 Arrow Function 綁定this 的scope 還有看到jq覺
08/27 08:58, 22F

08/27 08:58, 5年前 , 23F
得頭很痛 看你要不要改document.querySelector
08/27 08:58, 23F

08/27 09:30, 5年前 , 24F
都我的問題
08/27 09:30, 24F

08/28 17:28, 5年前 , 25F
asynchronize真的很整人,但也是很重要的基礎
08/28 17:28, 25F
文章代碼(AID): #1RVeBUF1 (Soft_Job)