问题
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)
回答1:
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
});
来源:https://stackoverflow.com/questions/17720846/how-to-define-instance-methods-for-models-with-sails-js