天天看點

關于富文本編輯器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 
    ... 
  }
});