我正在編寫一個帆布賽車遊戲,並計劃使用事件來確定每個遊戲對象何時被初始化並可以使用。首先,我嘗試將事件偵聽器添加到我的對象,但意識到它們只能附加到html元素。作爲解決方法,我添加了一個偵聽器到窗口對象。確定對象何時準備就緒。我應該使用事件嗎?
我會很感激我是否應該爲這個問題使用事件,以及是否有任何常見的模式/方法,我應該看看?我正在閱讀觀察者模式,這是否適合這種情況?
下面的代碼片段顯示了我目前正在做的事情。當Track對象的所有項目都被加載後,它將調度由附加到窗口對象的事件偵聽器捕獲的事件。
主營:
function game() {
var loadCount = 0;
var itemsToLoad = 10;
window.addEventListener("finishedLoading", itemLoaded, false);
function itemLoaded(event) {
loadCount++;
if(loadCount >= itemsToLoad)
{
gameStateFunction = title;
}
}
}
跟蹤對象:
function Track(name, bgTileSheet) {
this.backgroundImage = new Image();
this.itemsLoaded = 0;
this.itemsToLoad = 3;
this.loadedEvent = new CustomEvent("finishedLoading", {
detail: {
objectType: "track"
},
bubbles: true,
cancelable: false
});
this.centerPath = null;
}
Track.prototype.updateLoadProgress = function() {
this.itemsLoaded++;
if(this.itemsLoaded >= this.itemsToLoad)
{
dispatchEvent(this.loadedEvent);
}
};
Track.prototype.init = function() {
//calls loadItems() when XML data is ready
};
Track.prototype.loadItems = function() {
this.loadBackground();
this.loadMapDimensions();
this.loadPaths();
};
Track.prototype.loadBackground = function() {
var self = this;
this.backgroundImage.addEventListener("load",
function() {
self.updateLoadProgress();
},
false);
this.backgroundImage.src = Track.TILESHEET_DIR + this.bgTileSheet;
};