【问题标题】:Is there a better way to avoid duplicate lifecycle callbacks?有没有更好的方法来避免重复的生命周期回调?
【发布时间】:2014-04-22 17:37:40
【问题描述】:

Waterline 允许对模型进行一些生命周期回调,如下所示...

  • beforeValidation / fn(values, cb)
  • beforeCreate / fn(values, cb)
  • afterCreate / fn(newlyInsertedRecord, cb)
  • beforeValidation / fn(valuesToUpdate, cb)
  • 更新前/fn(valuesToUpdate, cb)
  • afterUpdate / fn(updatedRecord, cb)
  • beforeDestroy / fn(criteria, cb)
  • afterDestroy / fn(cb)

但是,如果我想在创建和更新之前采取行动怎么办?

Rails 有一个beforeSave,非常适合这个。 Sails.js 中有类似的东西吗?

我可以让两个回调都调用一个函数,但我想确定没有更好的方法。

【问题讨论】:

    标签: node.js sails.js waterline


    【解决方案1】:

    您可以从beforeCreate 调用beforeUpdate,反之亦然:

    beforeCreate: function(values, cb) {
        // Forward to the model's beforeUpdate method
        return User.beforeUpdate(values, cb);
    },
    
    beforeUpdate: function(valuesToUpdate, cb) {
        ...
    }
    

    请记住,通过update 调用发送的值可能与发送给create 的值不同;例如,不要依赖实例的 id 值可用!

    【讨论】:

    • 谢谢 Scott,是否有计划添加一些其他“Rails”样式的回调,例如 save
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    相关资源
    最近更新 更多