8

我已经建立了一个带有 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();
    })
  }

};
4

3 回答 3

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();
    })
  }

};
于 2014-01-25T11:39:10.533 回答
2

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

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

于 2013-12-04T17:04:39.817 回答
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')但它是模型的一个实例,因此您不能像“Lets try”字符串上的参数一样传递它。而不是它尝试分开执行此功能并将工作

于 2016-10-22T06:25:09.120 回答