這節(jié)我們閱讀vdom中有關(guān)樣式和事件的代碼。
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())
}
}
代碼并沒(méi)有什么難懂的,我們需要注意的是睡毒,對(duì)于屬性和樣式,并沒(méi)有刪除的函數(shù)冗栗。當(dāng)我們需要?jiǎng)h除某些樣式時(shí)演顾,只需把這些樣式的值設(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直接對(duì)應(yīng)于原生的函數(shù)。對(duì)于h5來(lái)說(shuō)钠至,對(duì)應(yīng)于同一目錄下的listener.js.
下次將分析vdom原理