我這個人有一個習慣,喜歡寫getter/setter豺谈,這樣的好處是在設置了某屬性值時會自動更新UI泣栈,省了不少事册烈,但是在cocosCreator里面更新UI的操作必須在onLoad事件觸發(fā)之后,如果不遵循這個原則骂倘,那么你訪問的節(jié)點很有可能是空眼滤。
例子代碼:
cc.Class({
extends: cc.Component,
properties: {
background: cc.Sprite,
bgImg: {
get () {
return this._bgImg;
},
set (value) {
if(this._bgImg!= value)
{
this._bgImg= value;
this.updateView();
}
},
visible: false
},
},
updateView(){
this.background.spriteFrame = this._bgImg;
},
});
每當我設置了上述代碼中的bgImg = xxx時都會導致updateView方法被調用來更新UI,即改變this.background的紋理稠茂。但是有時候在updateView方法被調用時我的onLoad方法還未被執(zhí)行柠偶,這時候this.background就是underfined,這樣的話就會導致報錯睬关。
好在cc.Component類里面提供了一個私有屬性叫做_isOnLoadCalled诱担,下面是官方API文檔對其的解釋:
_isOnLoadCalled
Number
返回一個值用來判斷 onLoad 是否被調用過,不等于 0 時調用過电爹,等于 0 時未調用蔫仙。
那么,借助該屬性丐箩,我們可以把代碼改為
cc.Class({
extends: cc.Component,
properties: {
background: cc.Sprite,
bgImg: {
get () {
return this._bgImg;
},
set (value) {
if(this._bgImg!= value)
{
this._bgImg= value;
if(this._isOnLoadCalled)//對onLoad是否已被調用的把關
{
this.updateView();
}
}
},
visible: false
},
},
//因為bgImg的setter中可能沒能執(zhí)行updateView摇邦,因此在onLoad中需要執(zhí)行該方法,哪怕updateView被執(zhí)行了兩遍也沒關系
onLoad(){
this.updateView();
}
updateView(){
this.background.spriteFrame = this._bgImg;
},
});