【问题标题】:accessing attributes in sequelize instanceMethods在 sequelize instanceMethods 中访问属性
【发布时间】:2015-07-09 13:49:19
【问题描述】:

我正在向 sequelize 模型添加一个实例方法。根据the documentation,我应该可以引用this.name,但我能看到的唯一值是this.dataValues.name。我没有理由相信高质量的文档是错误的......但为什么会发生这种情况?

此外,没有可用的 setter 或 getter。 this.getDataValue / this.setDataValue 在 getter / setter 中工作,但不在 instanceMethods 中。

我在网上找不到任何相关示例 - 如果您知道有一个项目可以读取(或更好地写入)这些值,请将其添加到您的回复中。

module.exports = (sequelize: Sequelize, DataTypes: DataTypes) => {
  return sequelize.define<UserInstance, UserPojo>('User', {
      name: { type: DataTypes.STRING }
    }, {
      instanceMethods: {
        myMethod: (value) => {

          // this.name is undefined

          // this.dataValues.name IS defined ??

        }
      }, ...

【问题讨论】:

    标签: express sequelize.js


    【解决方案1】:

    如您所见,我使用的是 Typescript。我刚刚检查了生成的 Javascript,立即发现了问题。

    Typescript 把它放在模块的顶部:

    var _this = this;
    

    并且引用了“_this”,而不是函数上下文中的那个——没有意识到这一点!一旦我将其更改为传统的 function() { } 语法,它就起作用了。所以,如果你使用打字稿,你可以这样做:

    myMethod: function(value: type) => void {
    
    }
    

    也就是说,您不必放弃输入参数和返回值。

    【讨论】:

      猜你喜欢
      • 2015-12-06
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      • 2011-11-23
      • 1970-01-01
      相关资源
      最近更新 更多