Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Кофе против PHP:
- ###
- # @lang CoffeeScript
- ###
- class Watcher
- @id = 0
- @events = []
- @observable = []
- @watch: (val = null) ->
- value = @observable[@id++] || undefined
- render= @events
- class Observable
- constructor: (val) ->
- value or=
- value: undefined
- before: []
- after: []
- return if val?
- fn value.value, val for fn in value.before
- value.value = val
- fn value.value, val for fn in value.after
- fn value.value, val for fn in render
- else
- value.value
- @before: (cb) ->
- value.before.push cb
- @
- @after: (cb) ->
- value.after.push cb
- @
- @subscribe: (cb) -> @after cb
- if val? then Observable val
- return Observable
- @subscribe: (cb) ->
- @events.push cb
- window.watch = ((v) -> Watcher.watch(v))
- # Вызов
- a = watch 42
- a.subscribe ->
- alert 'Оно изменилось!'
- a 23
- /**
- * @lang PHP
- **/
- class Watcher
- {
- const EVT_BEFORE = 'before';
- const EVT_AFTER = 'after';
- protected $value;
- protected $events = [
- self::EVT_BEFORE => [],
- self::EVT_AFTER => []
- ];
- public function __construct($val)
- {
- $this->value = $val;
- }
- public function __invoke($val = null)
- {
- if ($val !== null) {
- foreach($this->events[self::EVT_BEFORE] as $e) { $e($this->value); }
- $this->value = $val;
- foreach($this->events[self::EVT_AFTER] as $e) { $e($this->value); }
- }
- return $this->value;
- }
- public function before(callable $before)
- {
- $this->events[self::EVT_BEFORE][] = $before;
- }
- public function after(callable $after)
- {
- $this->events[self::EVT_AFTER][] = $after;
- }
- public function subscribe(callable $after)
- {
- $this->after($after);
- }
- }
- function watch($val = null) {
- return new Watcher($val);
- }
- $a = watch(42);
- $a->subscribe(function($v){
- // Значение изменилось!
- });
- $a(23);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement