关于富文本编辑器summernote的基本使用(四)

关于富文本编辑器summernote的基本使用(四)

summernote官方文档的翻译,有错误之处欢迎高手指正

模块化

summernote通过模块化支持功能的扩展。这种模块体系的建立受益于spring框架的启发。

关键术语
  • Module:模块
  • Context:Context包含modules和editor’s 声明的容器
  • Renderer:Renderer是用来创建元素的方法
  • UI:UI是用来新建ui元素的渲染函数
Module

Module是用来扩展功能的组件,具有生命周期,也有辅助函数和依赖于生命周期的函数

initialize

通过$(‘..’).summernote()进行初始化的时候会调用这个函数,可以用来在editor中绑定事件和创建元素

this.initialize = function () {
  // create button
  var button = ui.button({
    className: 'note-btn-bold',
    contents: '<i class="fa fa-bold">'
    click: function (e) {
      context.invoke('editor.bold'); // 调用editor中的bold方法
    }
  });

  // button.render()返回button生成的jquery对象
  this.$button = button.render();
  $toolbar.append(this.$button);
}
destroy

$(‘..’).summernote(‘destroy’)的时候调用这个方法,移除initlize即初始化时创建的元素,并解绑事件

this.destroy = function () {
  this.$button.remove();
  this.$button = null;
}
shouldInitialize

这个方法来决定模块是否会被初始化

// AirPopover's shouldInitialize
this.shouldInitialize = function () {
  return options.airMode && !list.isEmpty(options.popover.air);
};

下面是AutoLink 模块的完整代码

// Module Name is AutoLink
// @param {Object} context - states of editor
var AutoLink = function (context) {

  // you can get current editor's elements from layoutInfo
  var layoutInfo = context.layoutInfo;
  var $editor = layoutInfo.editor;
  var $editable = layoutInfo.editable;
  var $toolbar = layoutInfo.toolbar;

  // ui is a set of renderers to build ui elements.
  var ui = $.summernote.ui;

  // this method will be called when editor is initialized by $('..').summernote();
  // You can attach events and created elements on editor elements(eg, editable, ...).
  this.initialize = function () {
    // create button
    var button = ui.button({
      className: 'note-btn-bold',
      contents: '<i class="fa fa-bold">'
      click: function (e) {
        // invoke bold method of a module named editor
        context.invoke('editor.bold');
      }
    });

    // generate jQuery element from button instance.
    this.$button = button.render();
    $toolbar.append(this.$button);
  }

  // this method will be called when editor is destroyed by $('..').summernote('destroy');
  // You should detach events and remove elements on `initialize`.
  this.destroy = function () {
    this.$button.remove();
    this.$button = null;
  }
};
配置模块

可以通过option自定义模块

$(".summernote").summernote({
  modules: {
    myModule: MyModule
  }
});

可以通过暴露的API来调用自定义模块中的方法

$(".summernote").summernote("myModule.method", 'hello');
Plugin

可以以插件形式来自定义模块

// src/mymodule.js 
$.extend($.summernote.plugins, {
  myModule: function (context) {
    // define module 
    ... 
  }
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值