![](/img/trans.png)
[英]I have wrote two js scripts, both of them work but the problem is only the one placed second in the code will work
[英]Both render function have same code, but only one can work,why?
我想使用兩個render
函數來渲染兩個類。
class SidebarView {
constructor(model, root) {
this.root = root;
this.model = model;
model.addObserver(x => this.update(x));
}
render() {
this.root.innerHTML = `<span>${this.model.getNumberOfGuests()}</span>`;
}
update(whatHappened) {
this.root.secondElementChild.textContent = whatHappened.guests;
}
}
class SummaryView {
constructor(model, root) {
this.root = root;
this.model = model;
model.addObserver(x => this.update(x));
}
render() {
this.root.innerHTML = `Dinner for <span>${this.model.getNumberOfGuests()}</span> people`;
}
update(whatHappened) {
this.root.firstElementChild.textContent = whatHappened.guests;
}
}
class DinnerModel {
constructor() {
this.numberOfGuests = 2;
this.subscribers = [];
}
setNumberOfGuests(x) {
this.numberOfGuests = x;
this.notifyObservers({
guests: x
});
return x
// TODO TW1.1
}
getNumberOfGuests() {
return this.numberOfGuests // TODO TW1.1
}
addObserver(callback) {
this.subscribers.push(callback);
console.log(this.subscribers)
}
notifyObservers(whatHappened) {
for (let i = 0; i < this.subscribers.length; i++) {
return this.subscribers[i](whatHappened)
}
}
}
const model = new DinnerModel();
new SummaryView(model, document.body.querySelector("#summary")).render();
new SidebarView(model, document.body.querySelector("#sidebar")).render();
function onModelChange(payload) {
document.body.textContent = payload.guests;
}
model.addObserver(onModelChange);
這些代碼幾乎相同,但只有摘要可以很好地工作,我不知道為什么。
我可以在瀏覽器中看到數字 2,但對於側邊欄,我無法通過控制台更改數字。 只有摘要可以通過控制台更改數字。
提前致謝。由於我是 Javascript 的初學者,這可能是一個愚蠢的問題。
問題是notifyObservers()
在通知第一個訂閱者后返回。 你不應該在循環中return
,因為它會立即結束函數,並且永遠不會繼續與其他訂閱者一起。
只需呼叫訂閱者而不返回。
notifyObservers(whatHappened) {
for (let i = 0; i < this.subscribers.length; i++) {
this.subscribers[i](whatHappened)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.