Advertisement
Serafim

Untitled

Oct 28th, 2013
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.15 KB | None | 0 0
  1. Кофе против PHP:
  2.  
  3. ###
  4. # @lang CoffeeScript
  5. ###
  6. class Watcher
  7.   @id         = 0
  8.   @events     = []
  9.   @observable = []
  10.  
  11.   @watch: (val = null) ->
  12.     value = @observable[@id++] || undefined
  13.     render= @events
  14.  
  15.     class Observable
  16.       constructor: (val) ->
  17.         value or=
  18.           value:  undefined
  19.           before: []
  20.           after:  []
  21.  
  22.         return if val?
  23.           fn value.value, val for fn in value.before
  24.           value.value = val
  25.           fn value.value, val for fn in value.after
  26.           fn value.value, val for fn in render
  27.         else
  28.           value.value
  29.  
  30.       @before: (cb) ->
  31.         value.before.push cb
  32.         @
  33.  
  34.       @after: (cb) ->
  35.         value.after.push cb
  36.         @
  37.  
  38.       @subscribe: (cb) -> @after cb
  39.  
  40.  
  41.     if val? then Observable val
  42.     return Observable
  43.  
  44.   @subscribe: (cb) ->
  45.     @events.push cb
  46.  
  47. window.watch = ((v) -> Watcher.watch(v))
  48.  
  49.  
  50. # Вызов
  51. a = watch 42
  52. a.subscribe ->
  53.   alert 'Оно изменилось!'
  54. a 23
  55.  
  56.  
  57.  
  58.  
  59. /**
  60.  * @lang PHP
  61. **/
  62. class Watcher
  63. {
  64.     const EVT_BEFORE = 'before';
  65.     const EVT_AFTER  = 'after';
  66.  
  67.     protected $value;
  68.  
  69.     protected $events = [
  70.         self::EVT_BEFORE => [],
  71.         self::EVT_AFTER  => []
  72.     ];
  73.  
  74.     public function __construct($val)
  75.     {
  76.         $this->value = $val;
  77.     }
  78.  
  79.     public function __invoke($val = null)
  80.     {
  81.         if ($val !== null) {
  82.             foreach($this->events[self::EVT_BEFORE] as $e) { $e($this->value); }
  83.             $this->value = $val;
  84.             foreach($this->events[self::EVT_AFTER] as $e)  { $e($this->value); }
  85.         }
  86.         return $this->value;
  87.     }
  88.  
  89.     public function before(callable $before)
  90.     {
  91.         $this->events[self::EVT_BEFORE][] = $before;
  92.     }
  93.  
  94.     public function after(callable $after)
  95.     {
  96.         $this->events[self::EVT_AFTER][] = $after;
  97.     }
  98.  
  99.     public function subscribe(callable $after)
  100.     {
  101.         $this->after($after);
  102.     }
  103. }
  104.  
  105. function watch($val = null) {
  106.     return new Watcher($val);
  107. }
  108.  
  109. $a = watch(42);
  110. $a->subscribe(function($v){
  111.     // Значение изменилось!
  112. });
  113. $a(23);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement