簡體   English   中英

javascript自定義偵聽器-加載元素時

[英]javascript custom listener - when element is loaded

我有匿名函數,我將所有JavaScript代碼都包裝在了其中(main.js)。 我將全局變量傳遞給函數之一。 但是問題是在main.js加載后創建了變量。 我可以准備使用jQuery文檔,但是我不想等待整個文檔被加載。

main.js

(function(){
  function example(){
    alert(globalVariable)
  }
})();

和之后加載的phtml文件

<script>var globalVariable = 'example'</script>

有什么方法可以創建自定義偵聽器,當創建自定義偵聽器時,應該強制使用example()嗎? 這樣的事情(僅作為示例說明我需要什么):

main.js

(function(){
  listen(mycustomlistener){
    function example(){
      alert(globalVariable)
    }
  }
})();

phtml文件

<script>
var globalVariable = 'example'
create listener(mycustomlistener)
</script>

您期望的觸發因素在哪里? 是由您觸發還是由事件觸發或由更改觸發?

如果它是偵聽器/觀察者設計,那么您正在尋找。 您可以實現自己的方法,也可以使用ribs.wreqr中可用的方法。

http://zen-and-art-of-programming.blogspot.in/2013/12/backbonewreqr-jumpstart.html

同樣從以上代碼中,即使您創建了偵聽器,您的示例函數也不會被調用,因為它只是內部的functon聲明,而不是調用即使它

var eventAggregator = new Backbone.Wreqr.EventAggregator(); 


//Subscribe for the event! 
eventAggregator.on('eventName', function() { 
     (function example(){
         alert(globalVariable)
     })();            //observe the call i ve made here which is absent in urs!!!
}); 


//Raise the event! 
eventAggregator.trigger('eventName');

您還可以使用jquery觀察者和可觀察的

https://gist.github.com/addyosmani/1321768

這應該可以幫助您解決所需的問題。 http://jsbin.com/mugage/1/edit?html,js,輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM