如何在Sails / Waterline的生命周期callback中调用模型实例方法?

我用2个实例方法build立了一个简单的模型。 我如何在生命周期callback中调用这些方法?

module.exports = { attributes: { name: { type: 'string', required: true } // Instance methods doSomething: function(cb) { console.log('Lets try ' + this.doAnotherThing('this')); cb(); }, doAnotherThing: function(input) { console.log(input); } }, beforeUpdate: function(values, cb) { // This doesn't seem to work... this.doSomething(function() { cb(); }) } }; 

它看起来像自定义定义的实例方法不是被devise为在生命周期中被调用,而是在查询模型之后。

 SomeModel.findOne(1).done(function(err, someModel){ someModel.doSomething('dance') }); 

链接到文档中的示例 – https://github.com/balderdashy/sails-docs/blob/0.9/models.md#custom-defined-instance-methods

尝试在常规JavaScript中定义函数,这样可以从整个模型文件中调用它们,如下所示:

 // Instance methods function doSomething(cb) { console.log('Lets try ' + this.doAnotherThing('this')); cb(); }, function doAnotherThing(input) { console.log(input); } module.exports = { attributes: { name: { type: 'string', required: true } }, beforeUpdate: function(values, cb) { // accessing the function defined above the module.exports doSomething(function() { cb(); }) } }; 

doSomethingdoAnotherThing不是属性,是方法,必须在生命周期callback级别。 尝试这样的事情:

 module.exports = { attributes: { name: { type: 'string', required: true } }, doSomething: function(cb) { console.log('Lets try ' + "this.doAnotherThing('this')"); this.doAnotherThing('this') cb(); }, doAnotherThing: function(input) { console.log(input); }, beforeCreate: function(values, cb) { this.doSomething(function() { cb(); }) } }; 

在第二个地方,你试图发送来控制this.doAnotherThing('this'),但它是模型的一个实例,所以你不能像“Lets try”string中的参数那样传递它。 而不是它试图执行此function分开,将工作