Dojo 发布 - 订阅不工作

Dojo publish - subscribe not working

下面的代码是我想要做的事情的简单抽象 - 它处理 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 块中也没有。开发者控制台也没有显示任何错误。这是处理发布和订阅的正确方法吗?

你非常接近,但犯了一个小错误。您在 发布主题后 订阅了该主题,因此您没有捕捉到它。如果你把 pub 放在 sub 之后就可以了。

这是您的样本,稍作修改并附上注释:

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