如何编写风帆函数以在控制器中使用? [英] How can I write sails function on to use in Controller?

查看:27
本文介绍了如何编写风帆函数以在控制器中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于sails js的问题:

I have a question on sails js:

  1. 如何在模型上编写风帆函数以在控制器中使用?喜欢:
    • beforeValidation/fn(values, cb)
    • beforeCreate/fn(values, cb)
    • afterCreate/fn(newlyInsertedRecord, cb)

推荐答案

如果您确实尝试使用生命周期回调之一,则语法如下所示:

If you are actually trying to use one of the lifecycle callbacks, the syntax would look something like this:

var uuid = require('uuid');
// api/models/MyUsers.js
module.exports = {
  attributes: {
    id: {
      type: 'string',
      primaryKey: true
    }
  },

  beforeCreate: function(values, callback) {
    // 'this' keyword points to the 'MyUsers' collection
    // you can modify values that are saved to the database here
    values.id = uuid.v4();
    callback();
  }
}

否则,您可以在模型上创建两种类型的方法:

Otherwise, there are two types of methods you can create on a model:

  • 实例方法
  • 收集方法

放置在属性对象内的方法将是实例方法"(在模型的实例上可用).即:

Methods placed inside the attributes object will be "instance methods" (available on an instance of the model). i.e.:

// api/models/MyUsers.js
module.exports = {
  attributes: {
    id: {
      type: 'string',
      primaryKey: true
    },
    myInstanceMethod: function (callback) {
      // 'this' keyword points to the instance of the model
      callback();
    }
  }
}

这将被这样使用:

MyUsers.findOneById(someId).exec(function (err, myUser) {
  if (err) {
    // handle error
    return;
  }

  myUser.myInstanceMethod(function (err, result) {
    if (err) {
      // handle error
      return;
    }

    // do something with `result`
  });
}

放置在属性对象之外但在模型定义内的方法是集合方法",即:

Methods placed outside the attributes object but inside the model definition are "collection methods", i.e.:

// api/models/MyUsers.js
module.exports = {
  attributes: {
    id: {
      type: 'string',
      primaryKey: true
    }
  },

  myCollectionMethod: function (callback) {
    // 'this' keyword points to the 'MyUsers' collection
    callback();
  }
}

收集方法将像这样使用:

the collection method would be used like this:

MyUsers.myCollectionMethod(function (err, result) {
  if (err) {
    // handle error
    return;
  }

  // do something with `result`
});

附言关于this"关键字将是什么的评论假设您以正常方式使用这些方法,即以我在示例中描述的方式调用它们.如果您以不同的方式调用它们(即保存对方法的引用并通过引用调用方法),这些注释可能不准确.

P.S. the comments about what the 'this' keyword will be are assuming that you use the methods in a normal way, i.e. calling them in the way that I described in my examples. If you call them in a different way (i.e. saving a reference to the method and calling the method via the reference), those comments may not be accurate.

这篇关于如何编写风帆函数以在控制器中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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