- AMD规范:异步模块定义(Asynchronous Module Definition),它采用异步方式加载模块,模块的加载不影响它后面语句的运行。所有依赖这个模块的语句,都定义在一个回调函数中,等到加载之后,这个回调函数才会执行。
- AMD模块的写法
require.js加载的模块,采用AMD规范。也就是说,模块必须按照AMD的规定来写。
具体来说,就是模块必须采用特定的define()函数来定义。如果一个模块不依赖其他模块,那么可以直接定义在define()函数之中。
假定现在有一个math.js文件,它定义了一个math模块。那么,math.js就要这样写:
// math.js
define(function (){
var add = function (x,y){
return x+y;
};
return {
add: add
};});
加载方法如下:
// main.js
require(['math'], function (math){
alert(math.add(1,1));
});
如果这个模块还依赖其他模块,那么define()函数的第一个参数,必须是一个数组,指明该模块的依赖性。
define(['myLib'], function(myLib){
function foo(){
myLib.doSomething();
}
return {
foo : foo
};
});
当require()函数加载上面这个模块的时候,就会先加载myLib.js文件。
- Stroage(M):Shape数据CURD管理。
- Painter(V):canvas元素生命周期管理,视图渲染,绘画,更新控制。
- Handler(C):事件交互处理,实现完整dom事件模拟封装。
require(['bngraph'], function(bngraph) { // just init to get a bngraph Instance var bg = bngraph.init(document.getElementById('main')); // bg can be used now! ... } );
var CircleShape = require('bngraph/shape/Circle'); bg.addShape( new CircleShape({ style : { x : 100, y : 100, r : 50, color : 'rgba(220, 20, 60, 0.8)' } }) ); bg.render();
var CircleShape = require('bngraph/shape/Circle'); bg.addShape( new CircleShape({ style : {...}, // 图形元素上绑定事件 onmouseover : function(params) { concole.log('catch you!'); } }) ); // 全局事件 bg.on('click', function(params) {alert('Hello, bngraph!')});
bg.addShape(shapeA); // shapeA.zlevel = 0; (default) bg.addShape(shapeB); // shapeB.zlevel = 1; bg.render(); bg.modShape(shapeB.id, {color:'red'}); // Don't worry! Is merge! bg.refresh(); // Just the level 1 canvas has been refresh~
var CircleShape = require('bngraph/shape/Circle'); var myShape = new CircleShape({ zlevel : 1, style : { ... // color | strokeColor | text | textFont | ... }, draggable : true });
bg.addShape(newShape); bg.render(); bg.animate(newShape.id) .when(1000, { position : [300, 200] }) .when(2000, { position : [30, 400] }) .start('BounceOut');
function MyShape() { ... } bg.addShape( new MyShape({ // and use it! style : {...}, ... }) );