this.init = function() {
dojo.event.topic.subscribe("/mytopic", this, processMessages);
}
function processMessages(message) {
alert("Message: " + message.content);
}
}
var bar = new function() {
this.showMessage = function(message) {
dojo.event.topic.publish("/mytopic", {content: message});
}
}
foo.init();
bar.showMessage("Hello Dojo Master");
Publish/Subscribe方式提供了一种方法,即在某函数和方法被调用之后可以以事件的方式调用其它的函数和方法。connect()可被用于调用一些listener,而在源函数被调用
之前。在aspect-oriented编程技术中,这被称为"before advice",前面说到的之后被称为"after advice"。这些术语叫人糊涂,说得简单些,Dojo采用了这种方式用于某些由connetct()所支持的特殊场合中。dojo.event.connect("before", exampleObj, "foo", exampleObj, "bar");第一个参数可以是"before"和"after",其意义如词义。某些连接使用了 kwConnect() 看起来是这样的:
dojo.event.kwConnect({
type: "before",
srcObj: exampleObj,
srcFunc: "foo",
targetObj: exampleObj,
targetFunc: "bar"
});再看看另外一种通讯方式:around,它可使我们更改the calling signatures of functions和arguments for listeners。这样就把某个函数封装了起来,即让重用的代码不必更改却让它为我所用。但是这样做有点回归了C/C++里面的goto,虽然好用,但是少用为妙。例子如下:
function foo(arg1, arg2){
// ...
}
function aroundFoo(invocation){
if(invocation.args.length < 2){
// note that it's a real array, not a pseudo-arr
invocation.args.push("default for arg2");
}
var result = invocation.proceed();
// we could change the result here
return result;
}
dojo.event.connect("around", "foo", "aroundFoo");aroundFoo的参数是一个method-invocation对象。它包含了调用某个函数的全部信息:传递给某函数的参数和一个方法,proceed(),它把参数们传给它所封装的函数,并获得其运行结果。