【问题标题】:How can I call a model instance method in lifecycle callback in Sails/Waterline?如何在 Sails/Waterline 的生命周期回调中调用模型实例方法?
【发布时间】:2013-10-25 14:53:18
【问题描述】:

我已经建立了一个带有 2 个实例方法的简单模型。如何在生命周期回调中调用这些方法?

module.exports = {

  attributes: {

    name: {
      type: 'string',
      required: true
    }

    // Instance methods
    doSomething: function(cb) {
      console.log('Lets try ' + this.doAnotherThing('this'));
      cb();
    },

    doAnotherThing: function(input) {
      console.log(input);
    }

  },

  beforeUpdate: function(values, cb) {
    // This doesn't seem to work...
    this.doSomething(function() {
      cb();
    })
  }

};

【问题讨论】:

    标签: javascript node.js sails.js waterline


    【解决方案1】:

    doSomethingdoAnotherThing 不是属性,是方法,必须处于生命周期回调级别。试试这样的:

    module.exports = {
    
        attributes: {
    
            name: {
                type: 'string',
                required: true
            }
    
        },
    
        doSomething: function(cb) {
            console.log('Lets try ' + "this.doAnotherThing('this')");
            this.doAnotherThing('this')
            cb();
        },
    
        doAnotherThing: function(input) {
            console.log(input);
        },
    
        beforeCreate: function(values, cb) {
    
            this.doSomething(function() {
                cb();
            })
        }
    
    };
    

    在第二个地方,您正在尝试发送到控制台 this.doAnotherThing('this') 但它是模型的一个实例,因此您不能像“让我们尝试”上的参数一样传递它“ 细绳。而不是它尝试分开执行这个函数并且会工作

    【讨论】:

      【解决方案2】:

      尝试在常规 javascript 中定义函数,这样就可以从整个模型文件中调用它们,如下所示:

      // Instance methods
      function doSomething(cb) {
        console.log('Lets try ' + this.doAnotherThing('this'));
        cb();
      },
      
      function doAnotherThing(input) {
        console.log(input);
      }
      
      module.exports = {
      
        attributes: {
      
          name: {
            type: 'string',
            required: true
          }
        },
      
        beforeUpdate: function(values, cb) {
          // accessing the function defined above the module.exports
          doSomething(function() {
            cb();
          })
        }
      
      };
      

      【讨论】:

      • 刚刚注意到这个问题有点老了,希望它仍然可以帮助像我一样偶然发现它的人。
      【解决方案3】:

      看起来自定义定义的实例方法并非设计为在生命周期中调用,而是在查询模型之后调用。

      SomeModel.findOne(1).done(function(err, someModel){
         someModel.doSomething('dance')
      });
      

      文档中的示例链接 - https://github.com/balderdashy/sails-docs/blob/0.9/models.md#custom-defined-instance-methods

      【讨论】:

      • 这并没有解释你如何做到这一点。就我而言,他们真的应该内置这个,这是一个超级常见的用例。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-01
      • 2015-05-18
      • 2023-01-29
      相关资源
      最近更新 更多