javascript物件導向和回撥的一個示例

pengfoo發表於2013-09-04

這段程式碼是同事幫我寫的,覺得寫得很好,對JS初學的我來說,很有幫助,所以貼出來,大家一起學習。


function StrokeDrawer(orginalDatas) {
	var _strokeDatas = orginalDatas;
	var _currIndex = 0;
	var _callback;


	function _draw(){
		
		if(_currIndex < _strokeDatas.length) {
			
			var data = getStrokeData(_currIndex++);//prepare data
		
		
			setTimeout(function(){
				
				_doDraw(data);//真正畫點
				
				_draw(); //call next draw
					
			},1);
			
			
		}else{
			// draw complete
			
			if(_callback) {
				 _callback();
			}
		}
	}
	
	function getStrokeData(index){
		return _strokeDatas[index];
	}
	
	function _doDraw(data){
		
		// canvas draw
		
		console.log("往畫布上畫點", data);
	}

	
	this.beginDraw = function(callback){
		_callback = callback;
		_draw();
	}
}

var orginalDatas = ["橫","豎","撇","捺"];

var drawer = new StrokeDrawer(orginalDatas);
drawer.beginDraw(function(){
	console.log("我畫完了");
});


 

相關文章