2014-07-14 30 views
0

我有匿名函數,其中我包裹了所有的JavaScript代碼(main.js)。我將全局變量傳遞給其中一個函數。但問題是在加載main.js之後創建了變量。我可以使用jQuery文檔,但我不想等待整個文檔加載。JavaScript自定義偵聽器 - 當元素被加載

main.js

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

和PHTML文件,該文件後

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

裝載有什麼方法來創建自定義監聽器,當這個被創建實例()應強制?類似的東西(就像例子來說明什麼,我需要):

main.js

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

PHTML文件

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

回答

0

哪裏是你期望從觸發?它是由你引起的,還是來自事件或變化?

如果是你正在尋找的監聽/觀察者設計。你可以實現自己的或使用backbone.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

0

這應該幫助你在你想要的。 http://jsbin.com/mugage/1/edit?html,js,output

+0

「ready」應用整個DOM文檔,而不僅僅是任何DOM節點。我寫道,我不想等待整個文檔準備就緒。 – JohnyFree

+0

「但我不想等待整個文檔加載。」你從來沒有說過你不想等到整個DOM文檔被加載。您只需指定文檔。當我們談論的JavaScript將是$(document).ready(function(){});等待整個文檔加載。 $(「#input」)。ready(function(){});等待加載具有輸入ID的所有元素。 – PatchGuru

+0

我也認爲,但顯然不是這樣的。閱讀[這裏](http://stackoverflow.com/questions/5560654/onload-and-jquery-ready-do-they-work-on-any-dom-such-as-table-or-div) – JohnyFree