Почему не отображаются изменения в UI компоненте игры 2048?
Моя версия игры 2048 на чистом js использует pub/sub шаблон проектирования. Один из моих компонентов должен отображать изменения в UI и он это делает, но другой, написанный приблизительно таким же образом - нет. В чем их различие? (изменения в UI пока бутафорские - мне важно наладить коммуникацию между компонентами). В matrixView происходит изменение цвета (срабатывает колбек) когда я делаю клик. Такая же реализация summaryView не дает ничего. Фишка в том, что в summaryModel.subscribers - пусто. Подскажите пожалуйста. почему;
"Работающие" компоненты (только pub/sub логика): вид:
function MatrixView() {
// instantiates controller and a model
this.matrixModel = new MatrixModel();
this.controller = new Controller();
this.className = "table";
this.template = document.getElementById("matrixTemplate").innerHTML;
// creates a root element
BaseView.call(this);
}
// inherits
MatrixView.prototype = Object.create(BaseView.prototype);
MatrixView.prototype.constructor = MatrixView;
MatrixView.prototype.beforeRender = function () {
this.matrixModel.subscribe("changeState", this.changeColor, this);
};
MatrixView.prototype.afterRender = function () {
var newGameBtn = document.getElementById("newGameBtn");
newGameBtn.onclick = this.controller.onClickHandler.bind(this.controller);
window.addEventListener(
"keydown",
this.controller.onKeyDownHandler.bind(this.controller)
);
};
MatrixView.prototype.changeColor = function () {
document.getElementsByClassName("row")[0].style.backgroundColor = "black";
};
модель
function MatrixModel() {
BaseModel.call(this);
this.grid = [
["", "", "", ""],
["", "", "", ""],
["", "", "", ""],
["", "", "", ""],
];
var instance = this;
MatrixModel = function () {
return instance;
};
this.initFn();
}
MatrixModel.prototype = Object.create(BaseModel.prototype);
MatrixModel.prototype.constructor = MatrixModel;
// Action depends on user click New Game event
MatrixModel.prototype.startNewGame = function () {
this.publish("changeState");
}
;
Не работающая связка: модель:
function SummaryModel() {
BaseModel.call(this);
this.attributes = {
totalScore: 0,
bestScore: 0,
};
}
SummaryModel.prototype = Object.create(BaseModel.prototype);
SummaryModel.prototype.constructor = SummaryModel;
SummaryModel.prototype.reset = function () {};
SummaryModel.prototype.add = function () {
var i = 0;
console.log(this);
for (i in this.attributes) {
i = ++this.attributes[i];
}
this.publish("attrIncrease");
console.log(this.subscribers); // Тут пусто!!!
};
вид (должен отреагировать сменой цвета первого ряда, но этого не делает:
function SummaryView() {
this.summaryModel = new SummaryModel();
this.template = document.getElementById("summaryTemplate").innerHTML;
this.className = "summary";
BaseView.call(this);
}
SummaryView.prototype = Object.create(BaseView.prototype);
SummaryView.prototype.constructor = SummaryView;
SummaryView.prototype.beforeRender = function () {
this.summaryModel.subscribe("attrIncrease", this.display, this);
console.log(this.summaryModel.subscribers);
};
SummaryView.prototype.render = function () {
return templateStr(this.template, this.summaryModel.attributes);
};
SummaryView.prototype.afterRender = function () {};
SummaryView.prototype.display = function () {
document.getElementsByClassName("row")[0].style.backgroundColor = "blue";
};
Ну и мой pubSub
function PubSub() {
this.subscribers = [];
}
PubSub.prototype.subscribe = function (event, handler, context) {
this.subscribers.push({ event: event, handler: handler.bind(context) });
};
PubSub.prototype.publish = function (event, args) {
console.log(this.subscribers);
this.subscribers.forEach(function (action) {
if (action.event === event) {
action.handler(args);
}
});
};