您的位置:首页 > 移动开发 > Cocos引擎

lua cocos 界面金币更新

2016-07-24 22:14 381 查看
界面更新我们一般会用到事件通知。我觉得一般这种适合整个界面更新,若只更新界面的一小部分,要么像原来一样更新整个界面

要么单独放在一个事件通知。有时候也会觉得麻烦,比如我们游戏的金币更新,就只是一个label显示,

这里提供一个思路,我在游戏里对这些小的属性就是这么做的,比如说金币,我们可以吧显示金币的label与金币的data绑定到一起,然后金币发生改变时,

绑定的label 自动设置成新的数值,再也不用注册通知事件啦!data_role = {}
data_role.gold_coin = 0
data_role.holders = {
gold_coin = {}, --6 int32 金币
}
local holder_count = {
gold_coin = {count = 0}, --6 int32 金币
}

--holder为 显示金币的label 。attr_role = "gold_coin"
function data_role:addHolder(holder,attr_role,_add_str,_front_flag)

--增加的字符串 比如说 :金币1000 的 金币二字
_add_str = _add_str or ""
--增加的字符串是放在前面还是后面
_front_flag = (_front_flag==true)
holder._add_str = _add_str
holder._front_flag = _front_flag
--[[
c++ 应该要一个结构保存相应的数据,不像lua只要是个table就可以随意添加属性
--]]
--唯一标识
local tag = attr_role .. tostring(holder_count[attr_role].count)

--添加一个事件监听,移除控件时同时移除绑定
holder:addNodeEventListener(cc.NODE_EVENT, function (event)
if event.name == "cleanup" then
self.holders[attr_role][tag]=nil
end
end)

--防止被绑定在两个属性上
if holder._attr_role and holder._tag then
self.holders[holder._attr_role][holder._tag] = nil
end
self.holders[attr_role][tag] = holder
holder._attr_role = attr_role
holder._tag = tag

holder_count[attr_role].count = holder_count[attr_role].count+1

end
--金币label设置新的数值
function data_role:dealHolder(arg,attr_role)
for k,v in pairs(self.holders[attr_role]) do
if v._front_flag then
v:setString(v._add_str .. tostring(arg))
else
v:setString(tostring(arg) .. v._add_str)
end
end
end
--金币改变时,我们调用这个函数就可以
function data_role:changeAttr(arg,attr_role)
if self[attr_role] ~= arg then
self[attr_role] = arg
self:dealHolder(arg,attr_role)
end
end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cocos