成长相册项目小结----js

成长相册项目小结----js

最近忙着一个成长相册的项目,很赶时间。很忙。 终于接近尾声了。 这里对这个项目做一些总结。先总结一下js方面的东西。

一.jquery.lazyload.js 

这个项目一直跟图片打交道。这个必不可少。延迟加载。

使用方法   $("img").lazyload();   官网 http://www.appelsiini.net/projects/lazyload

做这个项目的时候 出了问题。 因为图片结构是横向的 然后 加了很多乱七八糟的事件。页面弄的很复杂。是通过触发事件来左右移动照片的。 结果导致了 延迟加载工作不正常。不知道是哪个东西导致的。就是有时候延迟加载正常工作。 有时候不能正常工作,。即使是把触发事件写成我自带的事件 仍然不能正常解决。 最后我在源代码里面加上了  $.fn.lazyloadUpdate=update; 然后 在自己的事件里面调用一下 lazyloadUpdate方法来实现延迟加载。 不知道有没有更好的方法。先暂时这么解决的。 接下来就是要好好读读源代码 理解一下这个插件的工作原理。

核心就是2个   

一个是update方法 这里循环所有延迟加载的图片。判断是否应该加载 如果应该加载。 就调用 appear事件: $this.trigger("appear");

appear 事件是自定义的一个事件  $self.one("appear", function() {}); 里面的逻辑就是将 scr值 设置成真正的图片路径。

看源代码的过程中 学到了一些以前不知道的东西。

1.首先就是 trigger 的使用。这个事我之前忽略的。以前很多时候 给一个东西加了某个事件。处理一堆显示效果逻辑。 某个时刻需要用代码触发一下。很纠结。 一般我就是用 $(this).click() 一下来触发click事件。 可是如果不是这种事件就麻烦了。 以后这种情况就可以使用trigger 来处理。

2.$(''<img />") 的使用 貌似 使用这个就是创建了一个img对象。以前要动态创建对象 我都是用原生的js 很麻烦 从来记不得 每次都百度。 以后可以用这个来创建html对象。(貌似 创建的img对象 设置src的值 可以加载图片 这个是以前不知道的)

                3. $.grep 方法 是删除集合里面的某个元素。 这个以前也没有怎么注意到。


二。swfUpload 

严格来说这不能说是js 因为是flash上传。

这个项目里面要用到多文件异步上传 主要是上传图片了和音频了。有进度条等的逻辑。 试用了一些ajax文件上传。 最后还是选择了这个。这个的兼容性要好很多 。 用法很简单:

var upload=new SWFUpload({
			// Backend Settings
			upload_url : "<@spring.url "/upload/doUpload" />",
			file_post_name : "myUploadFile",
			post_params: {"activityId" : "${activityId}","sessionId":"${sessionId!0}"},
			// File Upload Settings
			file_size_limit : "50000", // 50 Mb
			file_types : "*.bmp;*.jpg;*.jpeg;*.png;*.MP3;*.wav",
			file_types_description : "文件",
			//file_upload_limit : "10",
			//file_queue_limit : "10",

			// Event Handler Settings (all my handlers are in the Handler.js file)
			file_dialog_start_handler : fileDialogStart, //打开 选择文本
			file_queued_handler : fileQueued, //队列
			file_queue_error_handler : fileQueueError, //出错
			file_dialog_complete_handler : fileDialogComplete,//这里选择完成
			upload_start_handler : uploadStart,
			upload_progress_handler : uploadProgress,
			upload_error_handler : uploadError,
			upload_success_handler : uploadSuccess,
			upload_complete_handler : uploadComplete,

			button_image_url : "<@spring.url "/resources/images/add.png" /> ",
			button_placeholder_id : "addBtn",
			button_width : 105,
			button_height : 40,

			flash_url : "<@spring.url "/resources/js/fileUpload/swfupload.swf" />",

			debug : false
		});
会依次执行各种事件。相信看名字就能知道各个参数的意义。在各个回调方法里面 一般会用到2个非常有用的对象

var stats = this.getStats();以及

file对象。 基本上所有的状态属性 都在这2个对象中。

stats 记录着整个功能的 上传的 成功个数 失败个数 等等信息

file 记录着单个文件的大小 ,index ,id 等等信息。

下面把回调方法记录一下。主要是记录 参数

/* This is an example of how to cancel all the files queued up.  It's made somewhat generic.  Just pass your SWFUpload
object in to this method and it loops through cancelling the uploads. */
var isOutLimit=false;
var limitCount=99;
function cancelQueue(instance) {
	document.getElementById(instance.customSettings.cancelButtonId).disabled = true;
	instance.stopUpload();
	var stats;
	
	do {
		stats = instance.getStats();
		instance.cancelUpload();
	} while (stats.files_queued !== 0);
	
}

/* **********************
   Event Handlers
   These are my custom event handlers to make my
   web application behave the way I went when SWFUpload
   completes different tasks.  These aren't part of the SWFUpload
   package.  They are part of my application.  Without these none
   of the actions SWFUpload makes will show up in my application.
   ********************** */
function fileDialogStart() {
	/* I don't need to do anything here */
}
function fileQueued(file) {
	try {
		// You might include code here that prevents the form from being submitted while the upload is in
		// progress.  Then you'll want to put code in the Queue Complete handler to "unblock" the form
		var stats = this.getStats();
		var index=file.index;
		if(isOutLimit){
			return;
		}else if(index>limitCount){
			isOutLimit=true;
			return
		}
		
		var progressDiv=$('#progressDiv');
		var cloneDiv=$('#progressDiv .cloneProgress').clone(true);
		
		progressDiv.append(cloneDiv);
		cloneDiv.removeClass('cloneProgress');
		cloneDiv.addClass('progressChildrenDiv');
		cloneDiv.find('.fileName').text(file.name);
		
		cloneDiv.show();
		
		//var progress = new FileProgress(file, this.customSettings.progressTarget);
		//progress.setStatus("Pending...");
		//progress.toggleCancel(true, this);

	} catch (ex) {
		this.debug(ex);
	}

}

function fileQueueError(file, errorCode, message) {
	var index=file.index;
	if(isOutLimit){
		return;
	}else if(index>limitCount){
		isOutLimit=true;
		return
	}
	try {
		if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
			//alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
			return;
		}


		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			var progressDiv=$('#progressDiv');
			var cloneDiv=$('#progressDiv .cloneProgress').clone(true);
			
			progressDiv.append(cloneDiv);
			cloneDiv.removeClass('cloneProgress');
			cloneDiv.addClass('progressChildrenDiv');
			cloneDiv.find('.fileName').text(file.name);
			cloneDiv.find('.scoringBox_box').addClass('scoringBox_boxError').css('width','100%'); 
			cloneDiv.find('.scoringBox_backg ').removeClass('scoringBox_none').addClass('scoringBox_fail').text("文件已超过50M,请处理后上传");
			cloneDiv.show();
			break;
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			progress.setStatus("Cannot upload Zero Byte files.");
			this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			progress.setStatus("Invalid File Type.");
			this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
			//alert("You have selected too many files.  " +  (message > 1 ? "You may only add " +  message + " more files" : "You cannot add any more files."));
			break;
		default:
			if (file !== null) {
				progress.setStatus("Unhandled Error");
			}
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {	
	$('.noneTitle').hide();
	if(isOutLimit){
		alert('每次最多上传100个文件');
	}
	try {
		if (this.getStats().files_queued > 0) {
			//document.getElementById(this.customSettings.cancelButtonId).disabled = false;
		}
		/* I want auto start and I can do that here */
		this.startUpload();
	} catch (ex)  {
        this.debug(ex);
	}
}

function uploadStart(file) {
	var index=file.index;
	if(index>limitCount){
		this.cancelUpload(file.id)
		return false;
	}

	
	try {
		/* I don't want to do any file validation or anything,  I'll just update the UI and return true to indicate that the upload should start */
		//var progress = new FileProgress(file, this.customSettings.progressTarget);
		//progress.setStatus("Uploading...");
		//progress.toggleCancel(true, this);
		var index=file.index;
		$('#progressDiv .progressChildrenDiv:eq('+index+') .scoringBox_backg').removeClass('scoringBox_none');
		$('#progressDiv .progressChildrenDiv:eq('+index+') .scoringBox_backg').addClass('scoringBox_uping');
	}
	catch (ex) {
		console.log(JSON.stringify(ex))
	}
	
	return true;
}

function uploadProgress(file, bytesLoaded, bytesTotal) {

	try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
		
		var index=file.index;
		
		$('#progressDiv .progressChildrenDiv:eq('+index+') .scoringBox_box').css('width',percent+'%')

		//
		
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadSuccess(file, serverData) {
	try {
		var index=file.index;
		if(serverData=='success'){
			$('#progressDiv .progressChildrenDiv:eq('+index+') .scoringBox_backg').removeClass('scoringBox_uping ').addClass('scoringBox_done');		
		}else{
			
		}

	} catch (ex) {
		this.debug(ex);
	}
}

function uploadComplete(file) {
	try {
		/*  I want the next upload to continue automatically so I'll call startUpload here */
		if (this.getStats().files_queued === 0) {
			doUpdataSuccess();

			
		} else {	
			this.startUpload();
		}
	} catch (ex) {
		this.debug(ex);
	}

}

function uploadError(file, errorCode, message) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			progress.setStatus("Upload Error: " + message);
			this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
			progress.setStatus("Configuration Error");
			this.debug("Error Code: No backend file, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			progress.setStatus("Upload Failed.");
			this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.IO_ERROR:
			progress.setStatus("Server (IO) Error");
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			progress.setStatus("Security Error");
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			progress.setStatus("Upload limit exceeded.");
			this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
			progress.setStatus("File not found.");
			this.debug("Error Code: The file was not found, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
			progress.setStatus("Failed Validation.  Upload skipped.");
			this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			if (this.getStats().files_queued === 0) {
				document.getElementById(this.customSettings.cancelButtonId).disabled = true;
			}
			progress.setStatus("Cancelled");
			progress.setCancelled();
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			progress.setStatus("Stopped");
			break;
		default:
			progress.setStatus("Unhandled Error: " + error_code);
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}
开发过程有些注意的地方记录一下 

fileQueued 和 fileQueueError 在选择文件的时候必然会只执行一个。

如果设置了最大上传个数。 会直接进入error 我的需求是 超过最大上传个数 要提示 然后继续上前 100个 这里 我做了改动。

在 fileDialogComplete 即 对话框关闭的时候 判断文件个数 大于100 给提示。

在 uploadStart 的时候 判断 index  大于100 的 取消上传。 文档上面说 返回 false 就会不上传。 我试了一下 的确会不上传 但是 会不停的调用这个方法

死循环。 虽然看不出什么  但是个人感觉不好。 还是手动调用一下  this.cancelUpload(file.id) 这个就不在上传了。

另外 这个插件需要注意的是 在一些浏览器 (貌似主要是火狐) 是记不住 session 的。没上传一个文件 就开启一个新的session。如果 后台有安全验证 就需要 将sessionId 传到后台去。 然后通过sessionId获取 安全验证所需要的数据。


三 。jquery.jplayer.js

这个事因为上传的资源当中有音频播放。找了很多插件什么的。都会出各种各样的问题 要不是格式的事。要不是浏览器不兼容。最后选择了这个。很不错。(发现 js写的也挺多了 越来越i换jquery了 什么插件都有。)

用法特别简单 。还可以自定义样式。 不像其他的flash插件。 这个插件 页面完全就是 html 标签。 给每个div 加上对应的样式 就达到了控制的目的。

只有一个地方 让我出了一点问题。 貌似是火狐对MP3支持的问题。 我的项目 是需要支持 mp3 和 wav 2种格式。 supplied 这个参数 我就想当然的 设置成了“mp3,wav” 然后 在火狐上面就是出错。 然后改成 “MP3” 就好了。 我到现在还不是很懂。时间紧 就没有继续管。 估计这个参数配置的是哪些格式用flash解析?不是很确定。 另外需要注意的就是 swf 的path 不是路径。是到目录那一层。附上js代码。基本就是官方例子。


			$("#jquery_jplayer_1").jPlayer({
				ready: function (event) {
					$(this).jPlayer("setMedia", {
					mp3:bigUrl,
					wav:bigUrl
					});
				},
				play: function() {
					$(this).jPlayer("pauseOthers");
				},
				swfPath: "<@spring.url ""/>/resources/radio",
				supplied: "mp3",
				wmode: "window"
			});

四 。其他注意点

       1.这个问题已经祸害我很多次了 每次都忘了。 在所有的 ajax 。图片只要是有修改但是路径不变的,是向后台请求的 请一定要加上 随即参数。防止缓存。不要在某个浏览器上 发现没有缓存 就不加。 以后 在另外一个浏览器上发现缓存 会很后悔。。

亲身经历一个。本来不需要加随即参数的。因为这个页面是请求当前身份的一些其他数据。 然后有个功能 切换身份。在IE10 下就悲剧了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值