- I've split addCallback into two methods: before and after. I'm hoping this leans to a cleaner syntax, and people get less confused.
- Callbacks now are active 'by default'. If you define foo and add a callback to it, the callback will be executed when you do obj:foo(). If you don't wish this to happen, you must call obj:fooWithoutCallbacks() instead
Code: Select all
-- create a regular class, with two methods
Human = class('Human'):include(Callbacks) -- add the Callbacks module here
function Human:brushTeeth() print('Brushing teeth') end
function Human:sleep() print('ZZZ') end
-- insert two callbacks, before and after sleep
Human:before('sleep', 'brushTeeth')
Human:after('sleep', function() print('I got you, babe') end)
local peter = Human:new()
peter:sleep() -- normal call, prints 'Brushing teeth', 'ZZZ' and then 'I got you, babe'
peter:sleepWithoutCallbacks() -- call without callbacks, prints 'ZZZ'
- initialize and destroy are not "special" any more; they behave like any other method. Just beware that YourClass.new allways calls initialize, and never calls initializeWithoutCallbacks, unless you modify it somehow.
- Also, beware that when you do a before-initialize stuff, you will be dealing with objects not completely initialized. It's ok to do things like registering them on a list of instances, but attempting other things (using stuff that hasn't been initialized yet) can result in errors. Use after-initialize callbacks for that.