簡體   English   中英

如何在sails.js中向所有模型添加實例方法?

[英]How can I add an instance method to all Models in sails.js?

我想向所有將使用元數據的模型添加默認的toDisplay函數,這與屬性/關聯定義不同,是對實例的屬性/關聯執行操作,使其適合在UI中顯示。

例如:

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

因此,我也想為所有模型添加此功能。 我可以想象一個

Model.prototype.toDisplay = ... 

解決方案,但我不確定從何處獲取模型(有些長的require('waterline /..../ model')路徑?),如果我有Model,則將其放在哪里。

請指教。

在SailsJS.org上完整記錄模型配置。 @umassthrower指出在config/models.js添加實例方法會將其添加到所有模型中是正確的; 在觀察到這不是配置文件的預期用途時,他也是正確的。

在Sails中發現這比Rails更具挑戰性的原因是Ruby具有真實的類和繼承,而Javascript僅具有對象。 一種模擬繼承並從“基礎”對象擴展模型對象的相當干凈的方法是使用類似Lodash的_.merge函數 例如,您可以將基本模型保存在lib/BaseModel.js

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

  attributes: {

    someAttribute: 'string',

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

  }

};

然后在模型文件中,要求lodash並使用_.extend

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

  attributes: {

    someOtherAttribute: 'integer'

  }

};

基本模型中的屬性將與MyModel合並,其中MyModel優先。

在這里,將第一個參數設置為空模型{}很重要; _.merge對發送的第一個對象具有破壞性,因此,如果您剛剛進行了_.merge(BaseModel, {...}則將修改基本模型。

另外,記住要npm install lodash

這可以通過將函數添加到模型屬性中來完成,如下所示:

module.exports = {
    attributes: {
        attribute1: {
            type: String
        },
        attribute2: {
            type: String
        },
        toDisplay: function () {
            // your function here
        }

        // You can also override model functions like .toJSON or .toObject
        toJSON: function () {
            // your custom JSON here
        }
    }
}

Sails文檔的模型中 ,“屬性方法”下有更多信息。 值得注意的是,根據您的操作,可能根本不需要toDisplay()方法。 如果您僅嘗試格式化任何輸出或刪除任何敏感信息,則可以重寫toJSON()方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM