[英]Document.addEventListener “this” context
我正在編寫一個簡單的 CoffeeScript 類,但我遇到了此代碼的上下文問題:
class DragDrop
constructor: (@selector, @bodyDragEnterClass = "drag-over") ->
@attachEventHandlers()
attachEventHandlers: () ->
document.write(@bodyDragEnterClass) # this line tells me, that @bodyDragEnterClass is "drag-over"
document.addEventListener("dragenter", @onDragEnter, false)
onDragEnter: () ->
document.write(@bodyDragEnterClass) # this line tells me, that @bodyDragEnterClass is undefined
jQuery("body").addClass(@bodyDragEnterClass)
window.DragDrop = DragDrop
當調用attachEventHandlers
方法時, @bodyDragEnterClass
按預期設置為“拖動”。 但是,當觸發dragenter
事件並onDragEnter
方法時, @bodyDragEnterClass
為“未定義”。
我創建了一個 jsfiddle 來演示這里的上下文問題: http : //jsfiddle.net/SVvrM/
我該如何解決這個問題?
您有一個關於 CoffeeScript 中“粗箭頭”的經典案例。
您需要在不同上下文中執行的回調中訪問您的 DragDrop this
值。 使用onDragEnter
箭頭會將this
的當前值綁定到您的onDragEnter
函數:
# "fat arrow" function binding
onDragEnter: () =>
document.write(@bodyDragEnterClass) # this line tells me, that @bodyDragEnterClass is undefined
jQuery("body").addClass(@bodyDragEnterClass)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.