definitively removed middleclass from beholder. Refactorings

This commit is contained in:
Enrique García 2011-10-30 12:57:21 +01:00
parent 5b4b085156
commit 2daff1538b
3 changed files with 37 additions and 170 deletions

View File

@ -3,7 +3,7 @@
-- Copyright (c) 2011 Enrique García Cota -- Copyright (c) 2011 Enrique García Cota
-- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN callback OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
local beholder = {} local beholder = {}
@ -13,88 +13,90 @@ local function copy(t)
return c return c
end end
local function extractEventAndActionFromParams(params) local function extractEventAndCallbackFromParams(params)
local action = table.remove(params, #params) assert(#params > 0, "beholder:observe requires at least one parameter - the callback. You usually want to use two, i.e.: beholder:observe('EVENT', callback)")
return params, action local callback = table.remove(params, #params)
return params, callback
end end
local function findNodeById(self, id) local function findNodeById(self, id)
return self._nodesById[id] return self._nodesById[id]
end end
local function findOrCreateNode(self, event) local function findOrCreateChildNode(node, key)
local current = self._root node.children[key] = node.children[key] or { callbacks = {}, children = {} }
local key return node.children[key]
for i=1, #event do
key = event[i]
current.children[key] = current.children[key] or {actions={},children={}}
current = current.children[key]
end
return current
end end
local function executeNodeActions(node, params) local function findOrCreateDescendantNode(node, keys)
for i=1, #keys do
node = findOrCreateChildNode(node, keys[i])
end
return node
end
local function executeNodeCallbacks(node, params)
local counter = 0 local counter = 0
params = params or {} params = params or {}
for _,action in pairs(node.actions) do for _,callback in pairs(node.callbacks) do
action(unpack(params)) callback(unpack(params))
counter = counter + 1 counter = counter + 1
end end
return counter return counter
end end
local function executeAllActions(node) local function executeAllCallbacks(node)
local counter = executeNodeActions(node) local counter = executeNodeCallbacks(node)
for _,child in pairs(node.children) do for _,child in pairs(node.children) do
counter = counter + executeAllActions(child) counter = counter + executeAllCallbacks(child)
end end
return counter return counter
end end
local function executeEventActions(node, event) local function executeEventCallbacks(node, event)
local params = copy(event) local params = copy(event)
local counter = executeNodeActions(node, params) local counter = executeNodeCallbacks(node, params)
for i=1, #event do for i=1, #event do
node = node.children[event[i]] node = node.children[event[i]]
if not node then break end if not node then break end
table.remove(params, 1) table.remove(params, 1)
counter = counter + executeNodeActions(node, params) counter = counter + executeNodeCallbacks(node, params)
end end
return counter return counter
end end
local function addActionToNode(self, node, action) local function addCallbackToNode(self, node, callback)
local id = {} local id = {}
node.actions[id] = action node.callbacks[id] = callback
self._nodesById[id] = node self._nodesById[id] = node
return id return id
end end
local function removeActionFromNode(node, id) local function removeCallbackFromNode(node, id)
if not node then return false end if not node then return false end
node.actions[id] = nil node.callbacks[id] = nil
return true return true
end end
function beholder:reset() function beholder:reset()
self._root = { actions={}, children={} } self._root = { callbacks={}, children={} }
self._nodesById = setmetatable({}, {__mode="k"}) self._nodesById = setmetatable({}, {__mode="k"})
end end
function beholder:observe(...) function beholder:observe(...)
local event, action = extractEventAndActionFromParams({...}) local event, callback = extractEventAndCallbackFromParams({...})
return addActionToNode(self, findOrCreateNode(self, event), action) return addCallbackToNode(self, findOrCreateDescendantNode(self._root, event), callback)
end end
function beholder:stopObserving(id) function beholder:stopObserving(id)
return removeActionFromNode(findNodeById(self, id), id) return removeCallbackFromNode(findNodeById(self, id), id)
end end
function beholder:trigger(...) function beholder:trigger(...)
local event = {...} local event = {...}
local counter = (#event == 0) and executeAllActions(self._root) or executeEventActions(self._root, event) local counter = (#event == 0) and executeAllCallbacks(self._root) or executeEventCallbacks(self._root, event)
return counter > 0 and counter return counter > 0 and counter
end end

View File

@ -1,139 +0,0 @@
-- middleclass.lua - v2.0 (2011-09)
-- Copyright (c) 2011 Enrique García Cota
-- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-- Based on YaciCode, from Julien Patte and LuaObject, from Sebastien Rocca-Serra
local _classes = setmetatable({}, {__mode = "k"})
local function _setClassDictionariesMetatables(klass)
local dict = klass.__instanceDict
dict.__index = dict
local super = klass.super
if super then
local superStatic = super.static
setmetatable(dict, super.__instanceDict)
setmetatable(klass.static, { __index = function(_,k) return dict[k] or superStatic[k] end })
else
setmetatable(klass.static, { __index = function(_,k) return dict[k] end })
end
end
local function _setClassMetatable(klass)
setmetatable(klass, {
__tostring = function() return "class " .. klass.name end,
__index = klass.static,
__newindex = klass.__instanceDict,
__call = function(self, ...) return self:new(...) end
})
end
local function _createClass(name, super)
local klass = { name = name, super = super, static = {}, __mixins = {}, __instanceDict={} }
klass.subclasses = setmetatable({}, {__mode = "k"})
_setClassDictionariesMetatables(klass)
_setClassMetatable(klass)
_classes[klass] = true
return klass
end
local function _createLookupMetamethod(klass, name)
return function(...)
local method = klass.super[name]
assert( type(method)=='function', tostring(klass) .. " doesn't implement metamethod '" .. name .. "'" )
return method(...)
end
end
local function _setClassMetamethods(klass)
for _,m in ipairs(klass.__metamethods) do
klass[m]= _createLookupMetamethod(klass, m)
end
end
local function _setDefaultInitializeMethod(klass, super)
klass.initialize = function(instance, ...)
return super.initialize(instance, ...)
end
end
local function _includeMixin(klass, mixin)
assert(type(mixin)=='table', "mixin must be a table")
for name,method in pairs(mixin) do
if name ~= "included" and name ~= "static" then klass[name] = method end
end
if mixin.static then
for name,method in pairs(mixin.static) do
klass.static[name] = method
end
end
if type(mixin.included)=="function" then mixin:included(klass) end
klass.__mixins[mixin] = true
end
Object = _createClass("Object", nil)
Object.static.__metamethods = { '__add', '__call', '__concat', '__div', '__le', '__lt',
'__mod', '__mul', '__pow', '__sub', '__tostring', '__unm' }
function Object.static:allocate()
assert(_classes[self], "Make sure that you are using 'Class:allocate' instead of 'Class.allocate'")
return setmetatable({ class = self }, self.__instanceDict)
end
function Object.static:new(...)
local instance = self:allocate()
instance:initialize(...)
return instance
end
function Object.static:subclass(name)
assert(_classes[self], "Make sure that you are using 'Class:subclass' instead of 'Class.subclass'")
assert(type(name) == "string", "You must provide a name(string) for your class")
local subclass = _createClass(name, self)
_setClassMetamethods(subclass)
_setDefaultInitializeMethod(subclass, self)
self.subclasses[subclass] = true
self:subclassed(subclass)
return subclass
end
function Object.static:subclassed(other) end
function Object.static:include( ... )
assert(_classes[self], "Make sure you that you are using 'Class:include' instead of 'Class.include'")
for _,mixin in ipairs({...}) do _includeMixin(self, mixin) end
return self
end
function Object:initialize() end
function Object:__tostring() return "instance of " .. tostring(self.class) end
function class(name, super, ...)
super = super or Object
return super:subclass(name, ...)
end
function instanceOf(aClass, obj)
if not _classes[aClass] or type(obj) ~= 'table' or not _classes[obj.class] then return false end
if obj.class == aClass then return true end
return subclassOf(aClass, obj.class)
end
function subclassOf(other, aClass)
if not _classes[aClass] or not _classes[other] or aClass.super == nil then return false end
return aClass.super == other or subclassOf(other, aClass.super)
end
function includes(mixin, aClass)
if not _classes[aClass] then return false end
if aClass.__mixins[mixin] then return true end
return includes(mixin, aClass.super)
end

View File

@ -37,6 +37,10 @@ describe("Unit", function()
beholder:trigger("BAR", 2) beholder:trigger("BAR", 2)
assert_equal(3, counter) assert_equal(3, counter)
end) end)
it("throws an error if called without at least one parameter", function()
assert_error(function() beholder:observe() end)
end)
end) end)
describe(":stopObserving", function() describe(":stopObserving", function()