This repository has been archived by the owner on Sep 30, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Initial implementation of ObservableArray
- Loading branch information
1 parent
a157318
commit 709d147
Showing
1 changed file
with
74 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
require 'vienna/observable' | ||
|
||
module ObservableArray | ||
def self.infect(array) | ||
class << array | ||
alias :old_push :<< | ||
alias :old_clear :clear | ||
alias :old_insert :insert | ||
end | ||
|
||
array.extend self | ||
array.extend Vienna::Observable | ||
end | ||
|
||
def content | ||
self | ||
end | ||
|
||
def array_content_did_change(idx, remove, added) | ||
if observers = @array_observers | ||
observers.each do |obj| | ||
obj.array_did_change(self, idx, remove, added) | ||
|
||
end | ||
end | ||
|
||
attribute_did_change :size | ||
attribute_did_change :content | ||
attribute_did_change :empty? | ||
end | ||
|
||
def add_array_observer(object) | ||
(@array_observers ||= []) << object | ||
end | ||
|
||
def <<(obj) | ||
size = length | ||
old_push obj | ||
|
||
array_content_did_change size, 0, 1 | ||
self | ||
end | ||
|
||
def insert(idx, object) | ||
if idx > length | ||
raise ArgumentError, 'out of range' | ||
end | ||
|
||
old_insert idx, object | ||
|
||
array_content_did_change idx, 0, 1 | ||
self | ||
end | ||
|
||
def clear | ||
length = self.length | ||
old_clear | ||
|
||
array_content_did_change 0, length, 0 | ||
self | ||
end | ||
end | ||
|
||
class Array | ||
def add_observer(attribute, &blk) | ||
ObservableArray.infect(self) | ||
add_observer(attribute, &blk) | ||
end | ||
|
||
def add_array_observer(object) | ||
ObservableArray.infect(self) | ||
add_array_observer(object) | ||
end | ||
end |