Oct-17-2021, 09:54 PM
Sorry, I left off the events. Here's a more complete set of code:
Here's the full source of Bindable and BindableList:
from model import BindableList class Foo(BindableList): def __init__(self, name): super().__init__() self._name = name def __repr__(self): return self._name def item_removed(sender, *args): print("in handler:") for i in sender: print(i) if __name__ == "__main__": my_list = BindableList() my_list.bind(BindableList.ITEM_REMOVED, item_removed) o1 = Foo('1') o2 = Foo('2') o3 = Foo('3') my_list.append(o1) my_list.append(o2) my_list.append(o3) print("before remove") for i in my_list: print(i) my_list.remove(o2) print("in main code") for i in my_list: print(i)and the results of the run:
Output:before remove
1
2
3
in handler:
2
3
in main code
2
3
Process finished with exit code 0
As you can see, it was the first object (o1) that was deleted, rather than the second one (o2) despite calling my_list.remove(o2)Here's the full source of Bindable and BindableList:
class Bindable: def __init__(self): self.binds = {} def bind(self, event: str, callback): if event not in self.binds.keys(): self.binds[event] = list() self.binds[event].append(callback) def event_generate(self, event_type: str, event=None): if event_type not in self.binds.keys(): return for callback in self.binds[event_type]: if event is not None: callback(self, event) else: callback(self) class BindableList(Bindable, list): ITEM_APPENDED = "<<ITEM_APPENDED>>" ITEM_REMOVED = "<<ITEM_REMOVED>>" ITEM_INSERTED = "<<ITEM_INSERTED>>" def append(self, __object) -> None: super().append(__object) self.event_generate(BindableList.ITEM_APPENDED, __object) def remove(self, __value) -> None: super().remove(__value) self.event_generate(BindableList.ITEM_REMOVED, __value) def insert(self, __index: int, __object) -> None: super().insert(__index, __object) self.event_generate(BindableList.ITEM_INSERTED, (__index, __object))