如何在sails.js中为所有模型添加实例方法? [英] How can I add an instance method to all Models in sails.js?

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

问题描述

我想向所有模型添加默认的toDisplay函数,这些模型将使用元数据(与属性/关联定义不同)对实例的属性/关联进行操作,使其适合在UI中显示。

I'd like to add a default toDisplay function to all models which will use metadata, not unlike attribute/association definitions, to perform manipulations on the instance's attributes/associations making them suitable for display in the UI.

例如:

Foo.findOne(someId)
  .exec(function(err, foo) {
    ...
    res.view({
      foo: foo.toDisplay(),
    });
  });

所以,我想在所有模型中添加此功能。我可以想象一个

So, I'd like to add this function too all models. I can imagine a

Model.prototype.toDisplay = ... 

解决方案,但我不知道从哪里获取模型(一些长期需要('waterline /..../ model')路径?),以及如果我有模特,在哪里放那个剪辑。

solution, but I'm not sure where to get Model from (some long require('waterline/..../model') path?), and if I had Model, where to put that snip-it.

请告知。

推荐答案

模型配置已完整记录在SailsJS.org上。 @umassthrower指出将实例方法添加到 config / models.js 会将其添加到所有模型中是正确的。他也正确地认为这不是配置文件的预期用途。

Model configuration is fully documented here on SailsJS.org. @umassthrower is correct in pointing out that adding an instance method to config/models.js would add it to all of your models; he's also correct in observing that this is not the intended use of the config file.

你在Sails中发现这个比Rails更具挑战性的原因是Ruby有真正的类和继承,Javascript只有对象。模拟继承并从基础对象扩展模型对象的一种相当干净的方法是使用类似 Lodash的 _。合并功能。例如,您可以将基本模型保存在 lib / BaseModel.js 中:

The reason you're finding this a bit more challenging in Sails than Rails is that Ruby has real classes and inheritance, and Javascript just has objects. One fairly clean way to simulate inheritance and extend your model objects from a "base" object would be to use something like Lodash's _.merge function. For example you could save your base model in lib/BaseModel.js:

// lib/BaseModel.js
module.exports = {

  attributes: {

    someAttribute: 'string',

    someInstanceFunction: function() {
      // do some amazing (synchronous) calculation here
    }

  }

};

然后在你的模型文件中,需要 lodash 并使用 _.extend

Then in your model file, require lodash and use _.extend:

// api/models/MyModel.js
var _ = require('lodash');
var BaseModel = require("../../lib/BaseModel.js");
module.exports = _.merge({}, BaseModel, {

  attributes: {

    someOtherAttribute: 'integer'

  }

};

您的基本模型中的属性将与 MyModel MyModel 优先。

The attributes from your base model will be merged with MyModel, with MyModel taking precedence.

设置空模型的第一个参数 {} 在这里很重要; _。合并对发送的第一个对象具有破坏性,所以,如果您只是 _。合并(BaseModel,{...} ,那么基本模型将被修改。

Setting the first argument to the empty model {} is important here; _.merge is destructive for the first object sent in, so if you just did _.merge(BaseModel, {...} then the base model would be modified.

另外,记得 npm install lodash

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

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