Skip to content
This repository was archived by the owner on Sep 30, 2018. It is now read-only.

Commit 709d147

Browse files
committedFeb 7, 2014
Initial implementation of ObservableArray
1 parent a157318 commit 709d147

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
 

‎opal/vienna/observable_array.rb

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
require 'vienna/observable'
2+
3+
module ObservableArray
4+
def self.infect(array)
5+
class << array
6+
alias :old_push :<<
7+
alias :old_clear :clear
8+
alias :old_insert :insert
9+
end
10+
11+
array.extend self
12+
array.extend Vienna::Observable
13+
end
14+
15+
def content
16+
self
17+
end
18+
19+
def array_content_did_change(idx, remove, added)
20+
if observers = @array_observers
21+
observers.each do |obj|
22+
obj.array_did_change(self, idx, remove, added)
23+
24+
end
25+
end
26+
27+
attribute_did_change :size
28+
attribute_did_change :content
29+
attribute_did_change :empty?
30+
end
31+
32+
def add_array_observer(object)
33+
(@array_observers ||= []) << object
34+
end
35+
36+
def <<(obj)
37+
size = length
38+
old_push obj
39+
40+
array_content_did_change size, 0, 1
41+
self
42+
end
43+
44+
def insert(idx, object)
45+
if idx > length
46+
raise ArgumentError, 'out of range'
47+
end
48+
49+
old_insert idx, object
50+
51+
array_content_did_change idx, 0, 1
52+
self
53+
end
54+
55+
def clear
56+
length = self.length
57+
old_clear
58+
59+
array_content_did_change 0, length, 0
60+
self
61+
end
62+
end
63+
64+
class Array
65+
def add_observer(attribute, &blk)
66+
ObservableArray.infect(self)
67+
add_observer(attribute, &blk)
68+
end
69+
70+
def add_array_observer(object)
71+
ObservableArray.infect(self)
72+
add_array_observer(object)
73+
end
74+
end

0 commit comments

Comments
 (0)
This repository has been archived.