console
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class='wrapper'>
</div>
</body>
</html>
<script>
class LikeButton {
constructor () {
this.state = { isLiked: false }
}
setState (state) {
const oldEl = this.el
this.state = state
this.el = this.render()
if (this.onStateChange) {this.onStateChange(oldEl, this.el)}
}
changeLikeText () {
this.setState({isliked:!this.state.isLiked})
}
render () {
this.el = createDOMFromString(`
<button id='like-btn'>
<span class='like-text'>${this.state.isLiked ? '取消' : '点赞'}</span>
<span>��</span>
</button>
`)
this.el.addEventListener('click',
this.changeLikeText.bind(this)
)
return this.el
}
}
const createDOMFromString = (domString) => {
const div = document.createElement('div')
div.innerHTML = domString
return div
}
const wrapper = document.querySelector('.wrapper')
const likeButton = new LikeButton()
likeButton.onStateChange = (oldEl, newEl) => {
wrapper.insertBefore(newEl, oldEl)
wrapper.removeChild(oldEl)
}
wrapper.appendChild(likeButton.render())
console.log(likeButton)
</script>