這節(jié)我們閱讀vdom中有關樣式和事件的代碼。
Element.prototype.setAttr = function (key, value, silent) {
if (this.attr[key] === value) {
return
}
this.attr[key] = value
if (!silent && this.docId) {
const listener = instanceMap[this.docId].listener
listener.setAttr(this.ref, key, value)
}
}
Element.prototype.setStyle = function (key, value, silent) {
if (this.style[key] === value) {
return
}
this.style[key] = value
if (!silent && this.docId) {
const listener = instanceMap[this.docId].listener
listener.setStyle(this.ref, key, value)
}
}
Element.prototype.setClassStyle = function (classStyle) {
this.classStyle = classStyle
if (this.docId) {
const listener = instanceMap[this.docId].listener
listener.setStyles(this.ref, this.toStyle())
}
}
代碼并沒有什么難懂的,我們需要注意的是,對于屬性和樣式,并沒有刪除的函數(shù)。當我們需要刪除某些樣式時,只需把這些樣式的值設為初始值就可以了。
Element.prototype.addEvent = function (type, handler) {
if (!this.event[type]) {
this.event[type] = handler
if (this.docId) {
const listener = instanceMap[this.docId].listener
listener.addEvent(this.ref, type)
}
}
}
Element.prototype.removeEvent = function (type) {
if (this.event[type]) {
delete this.event[type]
if (this.docId) {
const listener = instanceMap[this.docId].listener
listener.removeEvent(this.ref, type)
}
}
}
Element.prototype.fireEvent = function (type, e) {
const handler = this.event[type]
if (handler) {
return handler.call(this, e)
}
}
這里面的handler直接對應于原生的函數(shù)。對于h5來說,對應于同一目錄下的listener.js.

下次將分析vdom原理