How to define instance methods for models with sails.js

隐身守侯 提交于 2019-12-04 00:18:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!