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