问题 如何使用sails.js为模型定义实例方法


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

在Waterline doc(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中的模型中,该函数未添加到对象中。 难道我做错了什么 ?

环境: 风帆(v0.8.94),节点(v0.8.16)


7956
2017-07-18 10:23


起源

在github中的sails repo中存在与此相对应的问题: github.com/balderdashy/sails/issues/578 - Adrien


答案:


您可以在具有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
});

14
2017-07-18 13:45



仅供参考:在Sails 0.12.3中仍然可以这样使用 - Ultrasaurus
尝试使用v1产生: Error: Functions are not allowed as attributes and instance methods on models have been removed. - Craig van Tonder