Revision 919
| trunk/code/projects/mapping/python/model.py (revision 919) | ||
|---|---|---|
| 1 |
import weakref |
|
| 2 |
|
|
| 3 |
_model_dependents=weakref.WeakKeyDictionary() |
|
| 4 |
def prchanged(what=None): |
|
| 5 |
print "Changed:",what |
|
| 6 |
|
|
| 7 |
class model(object): |
|
| 8 |
""" |
|
| 9 |
>>> def prchanged(what=None): |
|
| 10 |
... print "Changed",what |
|
| 11 |
... |
|
| 12 |
>>> m=model() |
|
| 13 |
>>> m.add_dependent(prchanged) |
|
| 14 |
>>> m.changed('foo')
|
|
| 15 |
Changed foo |
|
| 16 |
>>> def prchanged2(what=None): |
|
| 17 |
... print "Changed2",what |
|
| 18 |
... |
|
| 19 |
>>> m.add_dependent(prchanged2) |
|
| 20 |
>>> m.changed('foo')
|
|
| 21 |
Changed foo |
|
| 22 |
Changed2 foo |
|
| 23 |
>>> m.remove_dependent(prchanged) |
|
| 24 |
>>> m.changed('foo')
|
|
| 25 |
Changed2 foo |
|
| 26 |
|
|
| 27 |
""" |
|
| 28 |
|
|
| 29 |
def __init__(self): |
|
| 30 |
"No need to call" |
|
| 31 |
pass |
|
| 32 |
def dependents(self, create=0): |
|
| 33 |
"Return a list of my dependents" |
|
| 34 |
if not _model_dependents.has_key(self): # k in WeakDictionary broken in 2.2.3 |
|
| 35 |
if create: |
|
| 36 |
_model_dependents[self]=[] |
|
| 37 |
else: |
|
| 38 |
return () |
|
| 39 |
# If this fails, check self==self to see if compare works |
|
| 40 |
return _model_dependents[self] |
|
| 41 |
|
|
| 42 |
def changed(self,what=None): |
|
| 43 |
"Indicate that my data has changed, inform dependents" |
|
| 44 |
for x in self.dependents(0): |
|
| 45 |
x(what) |
|
| 46 |
|
|
| 47 |
def add_dependent(self,x): |
|
| 48 |
"Add a function to call with one argument (what) when I change" |
|
| 49 |
self.dependents(1).append(x) |
|
| 50 |
|
|
| 51 |
def remove_dependent(self,x): |
|
| 52 |
"Remove the function" |
|
| 53 |
self.dependents(1).remove(x) |
|
| 54 |
|
|
| 55 |
def clear_dependents(self): |
|
| 56 |
dep=self.dependents(0) |
|
| 57 |
if dep: |
|
| 58 |
dep[:]=[] |
|
Also available in: Unified diff