Saturday, December 3, 2011

Sencha Touch: Repeating tasks

And so, some trivia, dear reader (I tried to discover the etymology of 'dear reader' - and drew a blank). You may use Ext.defer on occasion, and perhaps even the DelayedTask class. But you need to fall back to 'raw' Javascript to create repeating tasks; so here is a trivial set of extensions to the Ext.util.Functions class that provide the ability to create repeating tasks, and some simple management of them. This use of base behaviour is not uncommon - how do you clear local storage? window.localstorage.clear().

 Ext.apply(Ext.util.Functions, {  
    repeat: function(taskName, fn, millis, zeroDayExecution) {
       this.tasks = this.tasks || {};  
       if (zeroDayExecution)  
          fn();  
       return this.tasks[taskName] = window.setInterval(fn, millis);  
   },  
   cancelRepeatingTask: function(taskName) {  
    if (this.tasks) {
      var id = this.tasks[taskName];  
      if (!Ext.isEmpty(id)) {  
         window.clearInterval(id);  
         delete this.tasks[taskName];  
      }
    }
   },  
   cancelAllRepeatingTasks: function() {  
    if (this.tasks)  
       Object.keys(this.tasks).forEach(function(key) { 
                                       this.cancelRepeatingTask(key); }, 
                                       this);         
   }  
 });  

No comments: