mxGraph淺入之 mxEditor

這次說一下mxGraph的核心類mxEditor,字面意思是編輯器,官方意思:一個繼承自mxEventSource類,爲了實現一個應用程序的、graph的包裝器。該類的可以註冊actions、結合mxCodec類實現I/O、集合mxLayoutManager類實現自動佈局、結合undoManager類實現undo和redo,還結合了標準對話框dialogs 和widgets等等。總之言之,該類特別重要。

舉個簡單的例子:

構建graph可以直接通過new mxGrpah(container)創建

// 結合了 vue, this.$refs,graph_container 爲容器
// 方式一
this.graph = new mxGraph(this.$refs.graph_container)

也可以通過mxEditor來創建

// 方式二
this.editor = new mxEditor()
this.graph = this.editor.graph
this.editor.setGraphContainer(this.$refs.graph_container);

但是兩種方式有哪些區別呢?

區別就是文章開頭提到的那些,mxEditor集成了好些方便的功能。

首先,方式二創建的graph,默認禁用了部分瀏覽器默認事件,比如鼠標右擊彈出框事件;默認添加了鼠標右擊拖動事件,按下鼠標右鍵拖動可以移動graph圖層;還有全選等操作,非常方便。

其次,在actions方面,方式二已經預先註冊好了大量現成的actions,直接通過action名稱調用即可。

// 頁面放大
// 方式一: 直接調用原始的頁面放大方法
this.graph.zoomIn()

//方式二: 通過事先註冊好的行爲name調用執行
this。editor.execute('zoomIn')

我們可以看一下mxEditor這個類的源碼:

function mxEditor(config)
{
	this.actions = [];
	this.addActions();
    ...
}

mxEditor的構造函數中有一個actions數組,和addActions方法,即通過addActions方法預先註冊好各種行爲,最後添加到actions中

mxEditor.prototype.addActions = function ()
{
	this.addAction('save', function(editor)
	{
		editor.save();
	});
	
	this.addAction('print', function(editor)
	{
		var preview = new mxPrintPreview(editor.graph, 1);
		preview.open();
	});
    // 行爲過多,省略
    ...
}
// addAction方法
mxEditor.prototype.addAction = function (actionname, funct)
{
    // 將行爲和行爲的名稱添加到數組
	this.actions[actionname] = funct;
};

// 預先註冊的行爲:
[ save、print、show、exportImage、refresh、cut、copy、paste、delete、group、ungroup、
removeFromParent、undo、redo、zoomIn、zoomOut、actualSize、fit、showProperties、
selectAll、selectNone、selectVertices、selectEdges、edit、toBack、toFront、enterGroup、
exitGroup、home、selectPrevious、selectNext、selectParent、selectChild、collapse、
collapseAll、expand、expandAll、bold、italic、underline、alignCellsLeft、
alignCellsCenter、alignCellsRight、alignCellsTop、alignCellsMiddle、alignCellsBottom、
alignFontLeft、alignFontCenter、alignFontRight、alignFontTop、alignFontMiddle、
alignFontBottom、zoom、toggleTasks、toggleHelp、toggleOutline、toggleConsole ]

mxEditor其他的方法,如createLayoutManager、getTitle、showOutline等方法,含義如其名,在此暫不詳解,有興趣可以去看源碼。

目前在不定期做一個vue + mxGraph的demo,後續若是用到了某個具體方法,再更新!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章