2016-07-10 11 views
1

Der folgende Code ist eine einfache Abstraktion von dem, was ich tun möchte - es befasst sich mit veröffentlichen und abonnieren Sie das Dojo-Ereignismodell. Mein Ziel ist es, ein Ereignis zu veröffentlichen und eine Methode für dieses Ereignis zu abonnieren.Dojo veröffentlichen - abonnieren funktioniert nicht

<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> 

Ich bekomme keine Warnungen, nicht einmal in Versuch und catch Blöcke. Entwicklerkonsole zeigt auch keine Fehler. Ist dies der richtige Umgang mit Publish und Subscribe?

Antwort

4

Sie sind sehr nah, aber haben einen kleinen Fehler gemacht. Sie abonnieren das Thema nach Sie veröffentlichen es, damit Sie es nicht fangen. Wenn du die Kneipe nach dem Sub platzierst, wird es funktionieren.

Hier ist Ihre Probe mit leichten Modifikationen und Kommentare:

<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> 
Verwandte Themen