11

如何为 Sails 中的对象定义函数/实例方法?

在 Waterline 文档(https://github.com/balderdashy/waterline)中,他们说:

var User = Waterline.Collection.extend({
...
  attributes: {
    ...
    // You can also define instance methods here
    fullName: function() {
      return this.firstName + ' ' + this.lastName
    }
  },
}

但是当我尝试在 Sails 模型的属性中定义实例方法时,该函数不会添加到对象中。难道我做错了什么 ?

环境:Sails (v0.8.94)、Node (v0.8.16)

4

1 回答 1

14

您可以使用sails 0.9.0 在模型中定义实例方法,如下所示:

module.exports = {
  attributes: {     
    name: {
      type: 'STRING',
      defaultsTo: 'zooname'
    },
    instanceMethod: function(){
      // your code
    }
  }
};

使用示例:

ClientHit.findOne({}).exec(function(err, model){
  model.instanceMethod(); //use your instance method
});
于 2013-07-18T13:45:32.513 回答