How can I call the model instance method in the lifecycle callback in Sails / Waterline?

I created a simple model with two instance methods. How can I call these methods in lifecycle callbacks?

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(); }) } }; 
+8
javascript waterline
source share
3 answers

It seems that the user-defined instance methods were not intended to be called in the life cycle, but after a model request.

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

Link to an example in the documentation - https://github.com/balderdashy/sails-docs/blob/0.9/models.md#custom-defined-instance-methods

+2
source share

Try to define functions in regular javascript, so they can be called from the whole model file as follows:

 // 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(); }) } }; 
+2
source share

doSomething and doAnotherThing are not attributes, they are methods and should be at the Lifecycle callback level. Try something like this:

 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(); }) } }; 

In second place, you are trying to send this.doAnotherThing ('this') to the console, but this is an instance of the model, so you cannot pass it as a parameter to the "Try to try" field. Instead, try this function separately and it will work

+1
source share

All Articles