远-方的博客

dojo Publish and Subscribe Events--dojo学习

 

dojo除了使用dojo.connect创建简单的系统事件以外,dojo还提供了对一些对象的匿名publication和subscription的支持,通过使用dojo.publish和

dojo.subcribe方法即可。这些方法允许一个函数把对象广播给任意其他已经subscribed(订阅)的函数,这就是dojo的topic系统,它可以使各独立组件非常容

易的实现相互通信,而不必去了解各组件的内部结构知识。
要使用dojo的topic系统,你需要了解三个函数:dojo.publish,dojo.subscribe,dojo.unsubscribe。dojo.publish可以调用通过dojo.subscribe连接到topic

系统的任意函数,传递给它们那些已published的参数。很显然,dojo.unsubscribe用来完成使一些函数不能再被dojo.publish调用的工作。

 

语法:

dojo.publish

dojo.publish(Topic Name [string], Arguments to Pass to Subscribed Function [array])

dojo.subscribe

handle = dojo.subscribe(Topic Name [string], Context of Linked Method [string or null], Linked Method [string or function])

dojo.unsubscribe

dojo.unsubscribe(Handle [handle object])

Example Code for Reference

function globalGuy(arg) { console.debug("Global Guy fired with arg " + arg); }
var someObject = {
   bar: function(first, second) { console.debug("Bar fired with first of "+first+" and second of "+second); return 7; },
}
}

Subscribing and Publishing Topics

To connect globalGuy to the topic "globalEvents" and someObject.bar to "fullNames", you simply use dojo.subscribe, as follows:

topics = [];
topics[0] = dojo.subscribe("globalEvents", null, globalGuy);
topics[1] = dojo.subscribe("fullNames", someObject, bar);

Note that the following alternative form would also work:

topics = [];
topics[0] = dojo.subscribe("globalEvents", globalGuy);
topics[1] = dojo.subscribe("fullNames", someObject, "bar");

To publish information to both of these topics, you pass dojo.publish the topic names and arrays of the arguments that you want to pass to subscribed functions, as follows

dojo.publish("globalEvents", ["data from an interesting source"]);
dojo.publish("fullNames", ["Alex", "Russell"]);

To disconnect someObject.bar from its topic, you use dojo.disconnect, as follows:

dojo.unsubscribe(topics[1]);

posted on 2009-11-15 12:03  远-方  阅读(1015)  评论(0编辑  收藏  举报

导航