See also: See also:
概要
使用模型钩子给扩展自PersistedModel的模型添加业务逻辑。钩子在指定事件的前后执行。
你可以定义下面的模型钩子。下面按模型生命周期的顺序把钩子作用于的事件列出来:
afterInitialize
- 在模型初始化之后触发beforeValidate
- 在模型执行验证之前触发afterValidate
- 在模型执行验证之后触发beforeSave
- 在模型被保存到数据源之前执行afterSave
- 在模型被保存到数据源之后执行beforeCreate
- 在模型创建之前执行afterCreate
- 在模型创建之后执行beforeUpdate
- 在模型更新之前执行afterUpdate
- 在模型更新之后执行beforeDestroy
- 在模型删除之前执行afterDestroy
- 在模型删除之后执行
afterInitialize
在模型初始化之后触发。
例子
... CoffeeShop.afterInitialize = function() { //your logic goes here }; ...
在执行一个动作前大多数的操作需要初始化一个model,但是有一些操作不会触发初始化事件,例如HTTP请求的exists
, count
, 和 bulk update 。
beforeValidate
在验证一个模型之前触发。
例子
... CoffeeShop.beforeValidate = function(next, modelInstance) { //your logic goes here next(); }; ...
modelInstance
参数是要被验证的模型实例。
必须在你添加的业务逻辑后调用next()
。
afterValidate
在验证一个模型之后触发。
例子
... CoffeeShop.afterValidate(next) { //your logic goes here next(); }; ...
必须在你添加的业务逻辑后调用next()
。
beforeCreate
在模型创建之前触发。
例子
... CoffeeShop.beforeCreate = function(next, modelInstance) { //your logic goes here next(); }; ...
modelInstance是要被创建的模型实例
。
必须在你添加的业务逻辑后调用next()
。
afterCreate
在模型创建之后触发。
例子
... CoffeeShop.afterCreate = function(next) { //your logic goes here this.name = 'New coffee shop name; //this就代表你创建的那个实例 next(); }; ...
必须在你添加的业务逻辑后调用next()
。
beforeSave
在模型实例保存之前触发。
例子
... CoffeeShop.beforeSave = function(next, modelInstance) { //your logic goes here next(); }; ...
modelInstance是要被保存的模型实例
。
必须在你添加的业务逻辑后调用next()
。否则应用会被挂起。
afterSave
在模型实例保存之后触发。
例子
... CoffeeShop.afterSave = function(next) { //your logic goes here this.name = 'New coffee shop name; //this就是你保存的那个实例 next(); }; ...
this就是你被保存的那个实例。
必须在你添加的业务逻辑后调用next()
。否则应用会被挂起。
beforeUpdate
在模型更新前触发。
例子
... CoffeeShop.beforeUpdate = function(next, modelInstance) { //your logic goes here next(); }; ...
modelInstance是要被更新的模型实例
。
必须在你添加的业务逻辑后调用next()
。否则应用会被挂起。
afterUpdate
在模型更新后触发。
例子
... CoffeeShop.afterUpdate = function(next) { //your logic goes here this.name = 'New coffee shop name; //this就是被更新的实例 next(); }; ...
this就是你被更新的那个实例。
必须在你添加的业务逻辑后调用next()
。否则应用会被挂起。
beforeDestroy
在模型删除前执行。
例子
... CoffeeShop.beforeDestroy = function(next, modelInstance) { //your logic goes here next(); }; ...
modelInstance是要被删除的模型实例
。
必须在你添加的业务逻辑后调用next()
。否则应用会被挂起。
afterDestroy
在模型删除后执行。
例子
... CoffeeShop.afterDestroy = function(next) { //your logic goes here next(); }; ...
必须在你添加的业务逻辑后调用next()
。否则应用会被挂起。