继承Sails.js模型的属性和生命周期功能 [英] Inherit attributes and lifecycle functions of Sails.js models

查看:41
本文介绍了继承Sails.js模型的属性和生命周期功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一组自定义的属性和生命周期方法,以在所有Sails.js模型之间共享.

I want to create a custom set of attributes and lifecycle methods that are shared between all my Sails.js models.

Sails.js通过调用 Waterline.Collection.extend()方法并提供在/api/models 内部找到的模型定义来自动创建和注册模型对象目录.

Sails.js automatically creates and registers the model objects by calling the Waterline.Collection.extend() method and providing the model definition found inside the /api/models directory.

从父级扩展模型定义的最佳方法是什么?我已经尝试过使用 _.extend(sails.config.model.parentModel,childModel),但是可悲的是 sails 对象并未全局公开(因为这是在加载orm之后完成的)钩).我还可以在所有模型中简单地 require()基本模型并将其扩展.

What would be the best way to extend my model definition from a parent? I already tried using _.extend(sails.config.model.parentModel, childModel) but sadly the sails object is not exposed globally (since this is done after loading the orm hook). I could also simply require() the base model in all my models and extend it.

与Sails搭配使用的干净方法是什么?

What would be a clean approach that goes well with Sails?

推荐答案

使用 config/models.js 为模型提供全局默认值是完全有效的.关于覆盖实例和类方法,根据我的测试,没有什么值得关注的.在模型定义中定义 sails.config.models 中存在的属性/方法将对此模型覆盖它,而不会将其保留为未定义.

Using config/models.js to provide global defaults for models is perfectly valid. Concerning overriding instance and class methods there is nothing fancy to watch out for according to my tests. Defining a property / method present in sails.config.models in a model definition will override it for this model, leaving it undefined won't.

定义:

// config/models.js
module.exports.models = {
  attributes: {
    // base model instanceMethod
    toJSON: function() {
      console.log('base.toJSON');
      return this.toObject();
    }
  },

  // base model classMethod
  test: function() {
    console.log('base.test');
  }
};


// api/models/first.js
module.exports = {
  attributes: {

  },

  // Overriding classMethods and lifecycle callbacks
  test: function() {
    console.log('first.test');
  }
};

// api/models/second.js
module.exports = {
  attributes: {
    // Overriding instance methods and attributes
    toJSON: function() {
      console.log('second.toJSON');
      return this.toObject();
    }
  },
}

测试

> sails.models.first.test();
>'first.test' // sails.config.models.test overridden

> sails.models.first.findOne(1).exec(err,res){ res.toJSON();  });
> 'base.toJSON' // sails.config.models.attributes.toJSON not overridden

> sails.models.second.test();
> 'base.test'; // sails.config.models.test not overridden

> sails.models.second.findOne(1).exec(err,res) { res.toJSON(); });
> 'second.toJSON' // sails.config.models.attributes.toJSON overridden

这篇关于继承Sails.js模型的属性和生命周期功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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