##// END OF EJS Templates
unidirectional link of traitlets
Sylvain Corlay -
Show More
@@ -227,6 +227,57 b' class link(object):'
227 (obj,attr) = key
227 (obj,attr) = key
228 obj.on_trait_change(callback, attr, remove=True)
228 obj.on_trait_change(callback, attr, remove=True)
229
229
230 @skip_doctest
231 class unilink(object):
232 """Link the trait of a source object with traits of target objects.
233
234 Parameters
235 ----------
236 source : pair of object, name
237 targets : pairs of objects/attributes
238
239 Examples
240 --------
241
242 >>> c = unilink((src, 'value'), (tgt1, 'value'), (tgt2, 'value'))
243 >>> src.value = 5 # updates target objects
244 >>> tgt1.value = 6 # does not update other objects
245 """
246 updating = False
247
248 def __init__(self, source, *targets):
249 self.source = source
250 self.targets = targets
251
252 # Update current value
253 src_attr_value = getattr(source[0], source[1])
254 for obj, attr in targets:
255 if getattr(obj, attr) != src_attr_value:
256 setattr(obj, attr, src_attr_value)
257
258 # Wire
259 self.source[0].on_trait_change(self._update, self.source[1])
260
261 @contextlib.contextmanager
262 def _busy_updating(self):
263 self.updating = True
264 try:
265 yield
266 finally:
267 self.updating = False
268
269 def _update(self, name, old, new):
270 if self.updating:
271 return
272 with self._busy_updating():
273 for obj, attr in self.targets:
274 setattr(obj, attr, new)
275
276 def unlink(self):
277 self.source[0].on_trait_change(self.update, self.source[1], remove=True)
278 self.source = None
279 self.targets = []
280
230 #-----------------------------------------------------------------------------
281 #-----------------------------------------------------------------------------
231 # Base TraitType for all traits
282 # Base TraitType for all traits
232 #-----------------------------------------------------------------------------
283 #-----------------------------------------------------------------------------
General Comments 0
You need to be logged in to leave comments. Login now