lk.Observer

.mixin (class)

local lib = {type='lk.Observer'} lib.__index = lib lk.Observer = lib local private = {}

assert(class.observed, 'The observed class should implement "observed(self, instance, event)"') assert(not class.notify, 'Existing "notify" method ("notify" is used by lk.Observer).') class.notify = private.notify class.observe = private.observe end

--- Start observing another class. Whenever the class notifies -- our ' function private:observe(instance) local observers = instance.observers if not observers then instance.observers = setmetatable({}, {__mode = 'k'}) observers = instance.observers end

-- We store observers in keys so that we are sure to only register -- each observer only once. observers[self] = true end

--- Whenever an event happens that should be notified to observers, this -- method should be called. function private:notify(action) local observers = self.observers if observers then for observer, _ in pairs(observers) do observer:observed(self, action) end end end