11

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)

Travis Webb
  • 14,688
  • 7
  • 55
  • 109
Adrien
  • 715
  • 6
  • 14
  • There is an issue corresponding to this in sails repo in github: https://github.com/balderdashy/sails/issues/578 – Adrien Jul 18 '13 at 11:03

1 Answers1

14

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
});
Adrien
  • 715
  • 6
  • 14