javascript – 嵌套的Web组件和事件处理
作者:互联网
我正在用javascript编写一个记忆游戏.我为这些卡制作了一个网络组件,< memory-card>以及包含卡片并处理游戏状态< memory-game>的网络组件. <存储卡> class包含其翻转时的图像路径,默认图像显示为卡的背面,其转动状态和onclick功能,以处理状态和图像之间的切换.
<记忆游戏> class有一个setter,它接收一组图像以生成< memory-cards>从.在< memory-game>中处理更新游戏状态的最佳方法是什么?类?我应该将附加事件监听器附加到< memory-card>那里的元素还是有更好的解决方法?我想要< memory-card>元素只能像现在一样处理自己的功能,即根据点击时的状态更改图像.
内存game.js
class memoryGame extends HTMLElement {
constructor () {
super()
this.root = this.attachShadow({ mode: 'open' })
this.cards = []
this.turnedCards = 0
}
flipCard () {
if (this.turnedCards < 2) {
this.turnedCards++
} else {
this.turnedCards = 0
this.cards.forEach(card => {
card.flipCard(true)
})
}
}
set images (paths) {
paths.forEach(path => {
const card = document.createElement('memory-card')
card.image = path
this.cards.push(card)
})
}
connectedCallback () {
this.cards.forEach(card => {
this.root.append(card)
})
}
}
customElements.define('memory-game', memoryGame)
内存card.js
class memoryCard extends HTMLElement {
constructor () {
super()
this.root = this.attachShadow({ mode: 'open' })
// set default states
this.turned = false
this.path = 'image/0.png'
this.root.innerHTML = `<img src="${this.path}"/>`
this.img = this.root.querySelector('img')
}
set image (path) {
this.path = path
}
flipCard (turnToBack = false) {
if (this.turned || turnToBack) {
this.turned = false
this.img.setAttribute('src', 'image/0.png')
} else {
this.turned = true
this.img.setAttribute('src', this.path)
}
}
connectedCallback () {
this.addEventListener('click', this.flipCard())
}
}
customElements.define('memory-card', memoryCard)
在Supersharp的回答之后实现自定义事件
memory-card.js(摘录)
connectedCallback () {
this.addEventListener('click', (e) => {
this.flipCard()
const event = new CustomEvent('flippedCard')
this.dispatchEvent(event)
})
}
记忆游戏.js(摘录)
set images (paths) {
paths.forEach(path => {
const card = document.createElement('memory-card')
card.addEventListener('flippedCard', this.flipCard.bind(this))
card.image = path
this.cards.push(card)
})
}
解决方法:
在< memory-card>中:
>使用CustomEvent()创建并使用dispatchEvent()调度自定义事件
在<记忆游戏>中:
>使用addEventListener()监听自定义事件
因为卡片嵌套在游戏中,所以事件会自然地冒泡到容器中.
这样,2个自定义元素将保持loosley耦合.
标签:javascript,web-component,dom-events,custom-element 来源: https://codeday.me/bug/20190727/1548959.html