How can I define functions/instance method for objects in Sails ?
In Waterline doc (https://github.com/balderdashy/waterline) they say:
var User = Waterline.Collection.extend({
...
attributes: {
...
// You can also define instance methods here
fullName: function() {
return this.firstName + ' ' + this.lastName
}
},
}
But when I try do define an instance method in attributes in a model in Sails, the function is not added to the object. Am I doing something wrong ?
Environment: Sails (v0.8.94), Node (v0.8.16)
Every model in Sails has a set of methods exposed on it to allow you to interact with the database in a normalized fashion. This is the primary way of interacting with your app's data. Since they usually have to send a query to the database and wait for a response, most model methods are asynchronous.
As of Sails v1.0, instance methods have been removed from Sails and Waterline. While instance methods like .save () and .destroy () were sometimes convenient in app code, in Node.js at least, many users found that they led to unintended consequences and design pitfalls. For example, consider an app that manages wedding records.
sails.js is an MVC (Model View Controller) web framework for node.js that emulates familiar MVC frameworks like Ruby on Rails. sails.js is based on Express and provides websocket support via socket.io. sails.js provides a set of conventions and default configurations to quickly get a new website project started.
Sequelize allows you to define instance methods for your model. Any instance method you define in the model can be called from the object returned by Sequelize query methods. There are two ways you can define instance methods with Sequelize: This tutorial will help you learn both ways, starting with adding a prototype function
You can define instance methods in models with sails 0.9.0 like this:
module.exports = {
attributes: {
name: {
type: 'STRING',
defaultsTo: 'zooname'
},
instanceMethod: function(){
// your code
}
}
};
Usage example:
ClientHit.findOne({}).exec(function(err, model){
model.instanceMethod(); //use your instance method
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With