|
MVVM的核心。它的作用是监听属性变化,当修改了model数据源里面的数据时,自动调用回调函数
---@class binding
binding = {}
---@alias binding_fun fun(val:any, old:any):void
-- ---绑定监听数据
---local b= binding.bindable(init)
---binding.watch(b,'属性',func)
---b.属性=值 即可触发 func
function binding.bindable(init)
local t = {}
local mt
mt = {
bind____ = {},
maxn____ = {}, -- no table.maxn in lua5.3
__index = function(table, key)
return mt[key]
end,
__newindex = function(table, key, value)
local v_old = mt[key]
-- if v_old == value then
-- return
-- end
mt[key] = value
local binds = mt.bind____[key]
if binds~=nil then
local maxn = mt.maxn____[key]
for i = 1, maxn do
local v = binds[i]
if type(v) == "function" then
v(value, v_old)
end
end
end
end
}
setmetatable(t, mt)
if type(init) == "table" then
for k, v in pairs(init) do
t[k] = v
end
end
return t
end
function binding.watch(table, key, func)
local binds = table.bind____
local maxns = table.maxn____
if not binds[key] then
binds[key] = {}
maxns[key] = 0
end
local bind = binds[key]
local tag = #bind + 1
bind[tag] = func
if tag > maxns[key] then
maxns[key] = tag
end
return tag
end
function binding.unwatch(table, key, tag)
local binds = table.bind____
if binds[key] then
binds[key][tag] = nil
end
end
|
|