2016-07-10 46 views
1

下面的代碼是我想要做的簡單抽象 - 它處理髮布和訂閱dojo事件模型。我的目標是發佈一個事件,併爲該事件訂閱一個方法。Dojo發佈 - 訂閱不工作

<html> 
<head> 
<script> 
dojoConfig={async:true, parseOnLoad: true} 
</script> 
<script type="text/javascript" src="dojo/dojo.js"> 
</script> 
<script language="javascript" type="text/javascript"> 
require(["dojo/topic","dojo/domReady!"], 

    function(topic){ 

    function somethod() { 
     alert("hello;"); 
    } 
    try{ 
     topic.publish("myEvent"); 
    } 
    catch(e){ 
     alert("error"+e); 
    } 

    //topic.publish("myEvent"); 
try{ 
topic.subscribe("myEvent", somethod); 

}catch(e){alert("error in subscribe"+e);} 
}); 
</script> 
</head> 
<body></body> 
</html> 

我沒有收到警報,即使在try和catch塊中也沒有。開發者控制檯也顯示沒有錯誤。這是處理髮布和訂閱的正確方法嗎?

回答

4

你很親密,但犯了一個小錯誤。您正在發佈之後訂閱這個主題,因此您無法抓住它。如果你把酒吧放在分支後面,它就會起作用。

這裏稍作修改和評論你的樣品:

<html> 
<head> 
<script> 
dojoConfig={async:true, parseOnLoad: true} 
</script> 
<!-- I used the CDN for testing, but your local copy should work, too --> 
<script data-dojo-config="async: 1" 
     src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"> 
</script> 
<script language="javascript" type="text/javascript"> 
require(["dojo/topic","dojo/domReady!"], 
function(topic){ 

    function somethod() { 
     alert("hello;"); 
    } 
    try{ 
     topic.publish("myEvent"); 
     /* ignored because no one is subscribed yet */ 
    } 
    catch(e){ 
     alert("error"+e); 
    } 

    try{ 
     topic.subscribe("myEvent", somethod); 
     /* now we're subscribed */ 

     topic.publish("myEvent"); 
     /* this one gets through because the subscription is now active*/ 

    }catch(e){ 
     alert("error in subscribe"+e); 
    } 
}); 
</script> 
</head> 
<body></body> 
</html>