суббота, 16 мая 2009 г.

javascript: "оконная" процедура обработки очереди сообщений (действий)

Сегодня, по-быстрому, написал объект, схожий с "оконной процедурой" на JavaScript, в частности для валидации формы в процессе набора текста. Я прекрасно знаю о различных фреймворках (frameworks) наподобие JQuery с кучей плагинов для решения подобного рода задач. Но в данном случае мне просто нужен был аналог setTimeout(checkFields, 900), но таким образом, чтобы выполнялась очередь подобных вызовов (схоже с оконной процедурой при программировании на WinApi). Собст-на единственной проблемой оказалось как раскрасить javscript-код:
  1. /**
  2. * MessageWindow Procedure
  3. * author: stash (for agroimpuls/openway way4-wb2 frontend-workaround)
  4. * created: 14 april 2009 16:00 - 17:00
  5. **/
  6. function /*queue element*/TAG_MESSAGE_QUEUE_ITEM(/* link to executable function */func_body,/* [delay]x[multiplier]=[delay] in ms before exec action */timeMultiplier,/* name of trigger to find him by string id and kill*/trig_name,/* number of execs before kill this trigger, can be undefined/null or zero if you don't want kill him */whenToDelete) {
  7.         this.func = func_body;
  8.         this.multiplier = timeMultiplier;
  9.         this.counter = 0;
  10.         this.trigger_name = trig_name;
  11.         this.delAfterCountExecs = whenToDelete;
  12.         this.nExecs = 0;
  13.         this.exec = function() { // executing action
  14.             if (++this.counter == this.multiplier) {
  15.                 this.counter = 0;
  16.                 this.func();
  17.                 this.nExecs++;
  18.                 if (typeof(this.delAfterCountExecs)!='undefined' &&
  19.                             this.delAfterCountExecs!=null &&
  20.                             this.nExecs == this.delAfterCountExecs)
  21.                     this.canDel = true;
  22.             }        
  23.         }            
  24.         this.canDel = false;
  25.         this.needRemove = function() {
  26.             return this.canDel;
  27.         }
  28. }
  29. WINDOW_PROC_MESSAGES /*message procedure wrapper*/ = {
  30.     /*minimal interval unit*/delay: 100/*ms*/,
  31.     processException: function(execption_object) {
  32.             if (typeof(report)!='undefined')
  33.                 report(execption_object.message,C_EXCEPTION)
  34.             else
  35.                 alert(execption_object.message);
  36.     },
  37.     window_proc: function() { // processing message queue
  38.         for (var i=0; i<WINDOW_PROC_MESSAGES.triggers.length; i++)
  39.             WINDOW_PROC_MESSAGES.exec(i);
  40.         setTimeout(WINDOW_PROC_MESSAGES.window_proc, 100); // self call
  41.     },
  42.     WINDOW_PROC:/* alias for window_proc*/ function() { WINDOW_PROC_MESSAGES.window_proc(); },
  43.     runned: false,
  44.     add: function(func, multiplier, t_name, del_after_exec_counts) {
  45.         WINDOW_PROC_MESSAGES.triggers[this.triggers.length] = new TAG_MESSAGE_QUEUE_ITEM(func, multiplier, t_name, del_after_exec_counts);
  46.         if (!WINDOW_PROC_MESSAGES.runned) {
  47.             WINDOW_PROC_MESSAGES.runned = true;
  48.             WINDOW_PROC_MESSAGES.window_proc();
  49.         }
  50.     },
  51.     remove: function(trigger_num_or_val) {
  52.         if (typeof(trigger_num_or_val)=='number')
  53.             WINDOW_PROC_MESSAGES.triggers.splice(trigger_num_or_val,1);
  54.         else {
  55.             for (var j=0; j<WINDOW_PROC_MESSAGES.triggers.length; j++) {
  56.                 if (typeof(WINDOW_PROC_MESSAGES.triggers[j].trigger_name)!='undefined' &&
  57.                         WINDOW_PROC_MESSAGES.triggers[j].trigger_name!=null &&
  58.                         WINDOW_PROC_MESSAGES.triggers[j].trigger_name == trigger_num_or_val)
  59.                     WINDOW_PROC_MESSAGES.triggers.splice(j,1);
  60.             }
  61.         }
  62.     },
  63.     exec: function(nTrigger) {
  64.         try {  WINDOW_PROC_MESSAGES.triggers[nTrigger].exec(); }
  65.         catch(e_obj) { WINDOW_PROC_MESSAGES.processException(e_obj); }
  66.         if (WINDOW_PROC_MESSAGES.triggers[nTrigger].needRemove())
  67.             WINDOW_PROC_MESSAGES.triggers.splice(nTrigger,1);
  68.     },
  69.     triggers: new Array()
  70. }
  71. //var wpm/* just alias*/=/*link to */WINDOW_PROC_MESSAGES;
  72. /** Window Message Procedure. **
  73. * I don't use there "this" pointer/link cause sometimes we have troubles
  74. * with visibility scope of variables (for examplr when method called from ajax-response procedure) 
  75. ************************************************************************************************/
* This source code was highlighted with Source Code Highlighter.