Monday, February 01, 2010

Javascript Prototype: En example of periodical event broadcaster with ajax

The class below executes script.php every 60 seconds. After successful execution, it throws an event "jobs:updated" with JSON data returned from script.php.

var NewBroadcaster = Class.create({
initialize: function(options) {
this.options = Object.extend({
refreshEvery: 60 // in seconds
}, options || {});
this.executer = new PeriodicalExecuter(this.update.bind(this),
this.options.refreshEvery
);
this.update();
},
update: function() {
this.request = new Ajax.Request("script.php", {
onSuccess: this.success.bind(this)
});
},
success: function(request) {
document.fire("jobs:updated", request.responseJSON);
}
});
view raw gistfile1.js hosted with ❤ by GitHub