为什么会有生命周期
- 为了规划代码
- 为了代码更好的可读性
- 为了提高代码的可维护性
通常开发一个MVVM的前端页面会涉及到 数据、初始化函数、计算属性、属性监听、交互事件、和后台进行ajax数据交换之类的代码。 生命周期就好比一个我们定义了一个抽屉,我们把代码进行分类后放到何时的抽屉之中,这样我们在开发和维护的时候大家的代码就都是一致的、统一的、可预期的。 从做产品长期维护的角度来看,会大大提升代码的可维护性。
关于生命周期钩子
- init:通常用于初始化页面,在页面初始化之前可以做任意的事情,比如在定义data时需要先从url里拿一些参数,或者在init里处理通用的页面行为分析统计等等。
- data:定义本地属性data的方法,类似与vue生命周期里的data
- computed: 定义计算属性的方法
- watch: 定义属性监听(ko.subscribe)方法
- methods: 定义页面事件监听方法
- beforeMounted: 一般用于将vm挂载到dom上的ko.applybindings
- mounted: 挂载之后, 通常页面业务处理的逻辑代码从这里开始
如何使用
import {BaseView} from 'ycloud-lifecycle'
import ko from 'knockout'
class View extends BaseView {
beforeInit () {
console.log('beforeInit')
}
// 初始化
init () {
console.log('page init')
}
afterInit () {
console.log('afterInit')
}
// 普通ko属性
data (params) {
this.title = ko.observable(params.title)
}
// 计算属性
computed () {
this.titleComputed = ko.computed(() => {
return this.title() + 'i am a boy'
})
}
// 属性监听
watch () {
this.title.subscribe((val) => {
console.log('watch title:' + val)
})
}
//事件 方法
methods () {
this.click = (data, evt) => {
console.log(data)
console.log(evt)
}
this.method1 = function (val, test) {
console.log(val + test)
}
}
beforeMounted () {
console.log('beforeMounted')
ko.applyBindings(this, document.getElementById('app'))
}
mounted () {
this.$on('testeventemmit', this.method1)
console.log('mounted' + this.title())
}
afterMounted () {
console.log('mounted' + this.title())
this.$emit('testeventemmit', 'i am emit', ' heyboy')
this.$off('testeventemmit', this.method1)
setTimeout(() => {
this.$emit('testeventemmit', 'i am emit', ' heyboy')
}, 2000)
}
}
new View({title: '新title:'})
update log:
- 2018-01-02 添加eventemitter2 增加$on,$emit,$off