Attach a callback to a publish
-
18-02-2021 - |
Question
I was wondering whether anyone knew of a way to attach an event/callback to a dojo publish when the event that is published completes.
I am publishing something as a delegated task, and when the delegated task completes I want to make some UI changes.
Let me know if you know how or if you know that it's not possible.
EDIT: I guess I could also do what I wanted if I was able to return a value to the publisher after the event published finishes.
Solution
I don't know of a "correct" way to do this but you could try using a separate channel and enforcing the connection "by convention":
dojo.subscribe('fooChannel', function(){
....
dojo.publish('fooChannelComplete', [...]);
});
A helper function to make this more seamless:
function add_to_foo(f){
dojo.subscribe('fooChannel', function(){
var ret = f.apply(this, arguments);
dojo.publish('fooChannelComplete', [ret]);
});
}
OTHER TIPS
Let's try something like this
// publisher side
var d = new dojo.Deferred();
dojo.publish("my/channel",[d]);
// ... do some extra asynchronous work , server request ...
result = goterror ? "error" : "ok";
if (!error) d.callback(result); else d.errback(result);
// listener side
dojo.subscribe("my/channel",function(d) {
// let's wait for the server to respond ( or maybe its already done )
d.then(function(result) {
// result is "ok"
},function(params) {
// result is "error"
});
});
Building on @Sebastien's premise:
//publisher
var deferred = new Dojo.deferred();
var successFunction = function(){
console.log('task succesfully completed');
};
var errorFunction = function(){
console.log('task did not succesfully complete');
};
//when our deferred object is done, invoke either successFunction or errorFunction
dojo.when(deferred, successFunction, errorFunction);
dojo.publish("someTopic",[deferred]);
//topic subscriber code
dojo.subscribe("someTopic",function(deferred) {
//do whatever delegated task is needed.
//...
//task completed successfully, invoke the `successFunction` defined on the publisher
deferred.callback();
//or if task did not complete successfully invoke `errorFunction` defined on the publisher
//deferred.errback();
});
Same premise, but using dojo.when
which IMO is nicer syntactic sugar.