2017-10-04 59 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