下面的代码是我想要做的简单抽象 - 它处理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块也没有。 Developer Console也没有显示错误。这是处理发布和订阅的正确方法吗?
答案 0 :(得分: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>