如何使用sails.js为模型定义实例方法 [英] How to define instance methods for models with sails.js

查看:22
本文介绍了如何使用sails.js为模型定义实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I define functions/instance method for objects in Sails ?

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

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
    }
  },
}

但是当我尝试在 Sails 的模型中的 attributes 中定义实例方法时,该函数没有添加到对象中.我做错了什么吗?

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 ?

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

Environment: Sails (v0.8.94), Node (v0.8.16)

推荐答案

你可以像这样在sails 0.9.0的模型中定义实例方法:

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
    }
  }
};

使用示例:

ClientHit.findOne({}).exec(function(err, model){
  model.instanceMethod(); //use your instance method
});

这篇关于如何使用sails.js为模型定义实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆