2017-10-04 56 views
0

我正在創建一個Javascript模塊,其任務基本上是通過點擊一個按鈕動態生成一個通過Ajax打開的模式。這個按鈕有一個數據屬性,我傳遞給Ajax調用來告訴它我想打開哪個模式。This Keywords * within * Javascript Module

這裏是模塊的簡化版本:

(function() { 

let modalwindow = { 

    init: function() { 
     this.bindEvents(); 
    }, 

    bindEvents: function() { 
     $(document).on('click', '[data-action="open-modal"]', this.ajaxCall.bind(this)); 
    }, 

    ajaxCall: function() { 

     $.ajax({ 

      url: ajax.url, 
      type: 'post', 
      context: this, 
      data: { 
       modal_id: this.modalID, // In this case, I need *this* to refer to the button 
       action: 'open_modal' 
      }, 
      success: function (response) { 

       // In this case, I need *this* to refer to the modalwindow object 

       this.openModal(response, this.modalID); 

      } 

     }); 

    }, 

    openModal: function(response, modalID) { 

     $(response).appendTo(Body).attr('data-state', 'active-modal'); 

    } 

} 

modalwindow.init(); 

})() 

問題是,在ajaxCall方法我需要的關鍵字指的是兩個不同的東西:我需要它來指按鈕時我設置了modal_id參數;我需要它引用模態窗口對象來調用成功的openModal方法。我怎麼做?

現在這個總是指模態窗口對象,其實openModal的作品;但modal_id參數是錯誤的,因爲在那裏這個應該參考按鈕。

我對Modular JS非常陌生,這一直讓我瘋狂。我發現了類似的問題,但似乎沒有解決模塊中所有方法的問題。

+1

[JavaScript關閉如何工作?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Salketer

+0

*「This Keyword * within * Javascript Module」* The單詞「模塊」現在在JavaScript中具有[特定的技術含義](https://tc39.github.io/ecma262/#sec-modules)(而在ES2015之前,它沒有,並且鬆散地用來指任何解決問題的不同方式的數量)。所以當我沒有提到實際的JavaScript模塊時,我會遠離它。 –

回答

2

設置處理程序時,您已經綁定了this,所以this將在ajaxCall中引用模態窗口。所以,接受事件的說法在ajaxCall

ajaxCall: function(e) { 

...然後在您需要的按鈕,使用e.currentTarget,並在您需要的模式窗口,使用this。在事件處理程序中,e.currentTarget(和this)都指代處理程序所連接的元素(而不是e.target,它指的是事件所針對的元素,可能是e.currentTarget的後裔)。

+0

像魅力一樣工作,非常感謝! – grazianodev