[英]JS: Split function into kind of module parts
我想通過構建某種模塊以更好的方式構造此代碼。 我正在使用ES6,因此嘗試使用import
/ export
。
示例功能
function() {
var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({
el: $('#canvas'),
width: 600,
height: 200,
model: graph,
gridSize: 1
});
var rect = new joint.shapes.basic.Rect({
position: { x: 100, y: 30 },
size: { width: 100, height: 30 },
attrs: { rect: { fill: 'blue' }, text: { text: 'my box', fill: 'white' } }
});
var rect2 = rect.clone();
rect2.translate(300);
var link = new joint.dia.Link({
source: { id: rect.id },
target: { id: rect2.id }
});
graph.addCells([rect, rect2, link]);
}
所以我想得到這樣的東西,它會更好地可讀:
script.js
import * from './config.js';
function() {
var graph = graph();
var paper = paper();
var rect = rect();
var rect2 = rect.clone();
rect2.translate(300);
var link = link();
graph.addCells([rect, rect2, link]);
}
並且所有內容應該在另一個文件中:
config.js
export
var graph = new joint.dia.Graph,
var paper = new joint.dia.Paper({
el: $('#canvas'),
width: 600,
height: 200,
model: graph,
gridSize: 1
});
// ...
但是這種嘗試的語法不正確。 應該怎么做?
您必須為導出的方法和導入的模塊命名。
試試這個代碼。
的script.js
import * as config from './config.js';
function() {
var graph = config.graph();
var paper = config.paper();
var rect = config.rect();
var rect2 = config.rect.clone();
rect2 = rect2.translate(300);
var link = config.link();
config.graph.addCells([rect, rect2, link]);
}
Config.js
export {graph as graph, paper as paper}
var graph = new joint.dia.Graph;
var paper = new joint.dia.Paper({
el: $('#canvas'),
width: 600,
height: 200,
model: graph,
gridSize: 1
});
// ...
但是這種嘗試的語法不正確。
你在找
export const graph = new joint.dia.Graph;
export const paper = new joint.dia.Paper({
el: $('#canvas'),
width: 600,
height: 200,
model: graph,
gridSize: 1
});
…
但是,您需要將它們包裝在函數中,以便導入模塊不會執行任何副作用,並且可以重用它們(在調用要創建的函數時多次調用它們)。 你會尋找
export function graph() {
return new joint.dia.Graph;
}
export function paper(graph) {
return new joint.dia.Paper({
el: $('#canvas'),
width: 600,
height: 200,
model: graph,
gridSize: 1
});
}
export function rect() {
return new joint.shapes.basic.Rect({
position: { x: 100, y: 30 },
size: { width: 100, height: 30 },
attrs: { rect: { fill: 'blue' },
text: { text: 'my box', fill: 'white' } }
});
}
export function link(rect1, rect2) {
return new joint.dia.Link({
source: { id: rect.id },
target: { id: rect2.id }
});
}
這樣你就可以使用
import {graph, paper, rect, link} from "…"
export default function() {
const g = graph(),
p = paper(g),
r1 = rect(),
r2 = r.clone();
r2.translate(300);
g.addCells([r1, r2, link(r1, r2)]);
}
但是,我認為您的代碼不會真正受益於跨多個模塊傳播。 只要您不能重用這些功能中的任何一個,就應該內聯它們,它們非常具體。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.