我对sails js有疑问:
如何在模型上编写sails函数?在Controler中使用?喜欢:
beforeValidation/fn(values,cb)
beforeCreate/fn(values,cb)
afterCreate/fn(newlyInsertedRecord,cb)
Chad McEllig.. 8
如果您实际上尝试使用其中一个生命周期回调,语法将如下所示:
var uuid = require('uuid'); // api/models/MyUsers.js module.exports = { attributes: { id: { type: 'string', primaryKey: true } }, beforeCreate: function(values, callback) { // 'this' keyword points to the 'MyUsers' collection // you can modify values that are saved to the database here values.id = uuid.v4(); callback(); } }
否则,您可以在模型上创建两种类型的方法:
实例方法
收集方法
放置在属性对象内的方法将是"实例方法"(在模型的实例上可用).即:
// api/models/MyUsers.js module.exports = { attributes: { id: { type: 'string', primaryKey: true }, myInstanceMethod: function (callback) { // 'this' keyword points to the instance of the model callback(); } } }
这将被用作:
MyUsers.findOneById(someId).exec(function (err, myUser) { if (err) { // handle error return; } myUser.myInstanceMethod(function (err, result) { if (err) { // handle error return; } // do something with `result` }); }
放置在属性对象外但在模型定义内的方法是"集合方法",即:
// api/models/MyUsers.js module.exports = { attributes: { id: { type: 'string', primaryKey: true } }, myCollectionMethod: function (callback) { // 'this' keyword points to the 'MyUsers' collection callback(); } }
收集方法将使用如下:
MyUsers.myCollectionMethod(function (err, result) { if (err) { // handle error return; } // do something with `result` });
PS关于'this'关键字将是什么的评论假设您以正常方式使用这些方法,即以我在示例中描述的方式调用它们.如果以不同的方式调用它们(即保存对方法的引用并通过引用调用方法),那些注释可能不准确.