【问题标题】:Own beforeSave handler for the apostrophe widget拥有撇号小部件的 beforeSave 处理程序
【发布时间】:2018-09-05 20:19:49
【问题描述】:

如何为撇号小部件编写 beforeSave() 处理程序?小部件 index.js 中的这段代码对我不起作用:

module.exports = {
  extend: 'apostrophe-widgets',
  label: 'My widget',
  addFields: [
  {
      name: 'label',
      type: 'string',
      label: 'Caption',
      required: true
  }
  ],
  construct: function(self, options) {

    self.beforeSave = function(callback) {
      console.log("beforeSave");
      return callback();
    }
  }
};

当我保存一个小部件的实例时,日志不会改变。是否可以为部件编写自己的 beforeSave() 处理程序?

【问题讨论】:

    标签: apostrophe-cms


    【解决方案1】:

    小部件只是文档的一部分,文档作为一个单元保存到数据库中,而不是单个小部件。所以没有beforeSave

    但是,如果您想要在每次对小部件进行清理以便可能包含在可能保存的文档中时采取一些措施,请查看sanitize 方法:

    self.sanitize = function(req, input, callback) {
      var output = self.apos.schemas.newInstance(self.schema);
      var schema = self.allowedSchema(req);
      output._id = self.apos.launder.id(input._id) || self.apos.utils.generateId();
      return self.apos.schemas.convert(req, schema, 'form', input, output, function(err) {
        if (err) {
          return callback(err);
        }
        output.type = self.name;
        return callback(null, output);
      });
    };
    

    注意此方法如何获取浏览器提供的数据input,并通过apos.schemas.convert 运行它以仅将有效数据复制到output。然后它将output 发送给它的回调。

    我们可以使用“超级模式”在这个过程结束时进行更改。例如,富文本小部件通常没有架构,它们只有一个包含标记的content 属性。但是,他们可能在某些网站上也有模式。下面是apostrophe-rich-text-widgets 模块如何使用“超级模式”扩展sanitize 方法以接受附加内容,同时不失去保存架构内容的能力:

    var superSanitize = self.sanitize;
    self.sanitize = function(req, input, callback) {
      return superSanitize(req, input, function(err, output) {
        if (err) {
          return callback(err);
        }
        output.content = sanitizeHtml(input.content, self.options.sanitizeHtml);
        return callback(null, output);
      });
    };
    

    注意:

    • 该方法的原始版本在变量superSanitize 中捕获。然后分配一个新函数作为方法。
    • 调用了superSanitize的原始版本。如果失败,我们会先处理。
    • output 已修改。您对output 所做的任何更改都将直接进入文档中的小部件,因此请确保验证您从input 接受的任何内容。浏览器(以及黑客编写的脚本)可能会撒谎。
    • 我们以与原始方法相同的方式结束:使用(null, output) 调用回调。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      相关资源
      最近更新 更多