旧代码回顾:YUI-ext 代码两侧/XML 数据岛/WSC 组件化

YUI-ext 代码两侧

旧时,写 yuiext 的代码的时候便学习过这些代码,两侧都是制作动画的代码。时间大概是两年前左右(07年初),但心路历程感觉是过了许久 呵呵,真的有天上十天,地下十年的感觉。那时候,靠自学,瞎浑的什么的都不懂,往这几句 script 撞呀撞呀,撞到做出效果为止!这不,一番经历,好歹也认识不少:JS 的道路并不坦,学 ajax 真的要下苦功!

言毕,丑汉终需见家翁,呵呵。下是那时稚嫩的代码。

var fade_in_pic = function() { var pic = Array(); pic[0] = "images//china.gif"; pic[1] = "images//Greece.gif"; pic[2] = "images//Italy.gif"; var img = Array(); for (i in pic) { img[i] = new Image(); // 这里有一丝不解,为什么Image会在这里成关键字? img[i].src = pic[i]; } var loop; var j = 0; return { ss: function() { var animator = new YAHOO.ext.Animator(); var cursor = new YAHOO.ext.Actor('holder', animator); animator.startCapture(); // pause .5 seconds animator.pause(4); cursor.fade(1); cursor.appear(); animator.play(); $("holder").src = img[j].src j += 1; if (j > pic.length - 1) j = 0; loop = setTimeout("fade_in_pic.ss()", 5000) } } } (); YAHOO.util.Event.addListener(window, "load", fade_in_pic.ss);

var side_show = { init: function() { var animator = new YAHOO.ext.Animator(); // start capturing var effect = new YAHOO.ext.Actor("img1", animator); var effect_next = new YAHOO.ext.Actor("img2", animator); animator.startCapture(); effect_next.hide(); animator.beginSync(); effect.pulsate(5); effect.fade(); animator.endSync(); animator.pause(2); //中断 effect_next.show(); animator.addAsyncCall(function() { alert(); }, 1); animator.pause(2); //中断 effect.fade(); animator.play(); //play()一定放最后 effect = null; } } YAHOO.util.Event.addListener(window, "load", side_show.init);

XML数据岛 with 分页

纯客户端解决方案,呵呵在当年还是蛮实用的技巧,出来的效果也是“无刷新”的加载XML,包括可分页。就是这份小脚本,小弟愚钝,啃了不少的时间。删掉怪可惜,放这儿算是一份纪念帖吧

function loadxml() { var xDoc = null; //Browser Version if (document.implementation && document.implementation.createDocument) { xDoc = document.implementation.createDocument("", "", null); //alert("体验更佳效果,请使用IE浏览器.版本5.0或以上."); var req = new XMLHttpRequest(); //make a instance for loading XML files(loacl or Remote req.open("GET", "web_config.xml", false); req.send(null); // print the name of the root element or error message var dom = req.responseXML; dump(dom.documentElement.nodeName == "parsererror" ? "error while parsing" : dom.documentElement.nodeName); new Insertion.Bottom('obj_title', dom.getElementsByTagName('title')[0].firstChild.data); //alert(dom.getElementsByTagName('title')[0].firstChild.data) return; } else if (typeof ActiveXObject != "undefined") { var msXmlAx = null; try { msXmlAx = new ActiveXObject("Msxml2.DOMDocument"); } catch (e) { msXmlAx = new ActiveXObject("Msxml.DOMDocument"); } xDoc = msXmlAx; } if (xDoc == null || typeof xDoc.load == "undefined") { xDoc = null; } xDoc.async = false; xDoc.load("web_config.xml"); root = xDoc.documentElement; } // function loadxml() { //loadxml 1 = it's IE; // var xDoc=null; //Browser Version // if (document.implementation && document.implementation.createDocument){ // xDoc=document.implementation.createDocument("","",null); // alert("体验更佳效果,请使用IE浏览器.版本5.0或以上."); // // for FF reading XML // //var req = new XMLHttpRequest(); //make a instance for loading XML files(loacl or Remote //req.open("GET", "web_config.xml", false); //req.send(null); //// print the name of the root element or error message //var dom = req.responseXML; //dump(dom.documentElement.nodeName == "parsererror" ? "error while parsing" : dom.documentElement.nodeName); //var ddd = dom.getElementsByTagName('title')[0].firstChild.data; ////alert(dom.getElementsByTagName('title')[0].firstChild.data) // return(loadxml = false;); // }else if (typeof ActiveXObject != "undefined"){ // var msXmlAx=null; // try{msXmlAx=new ActiveXObject("Msxml2.DOMDocument");} // catch (e){msXmlAx=new ActiveXObject("Msxml.DOMDocument");} // xDoc=msXmlAx; // } // if (xDoc==null || typeof xDoc.load=="undefined"){xDoc=null;} // // xDoc.async = false; // xDoc.load("web_config.xml"); // root = xDoc.documentElement; // return(loadxml = true); // } function list(page) { try { var loading = $("loading"); loading.style.display = "none"; var bigclass = $("bigclass"); //there's problem :Select alway over the DIV... bigclass.style.display = ""; var objXML = document.getElementById("Detailsdso"); var rs = objXML.recordset; rs.pagesize = 4 //new_pagesize(); //获取每页显示条目数量 var dd = objXML.recordset.pagecount; var rc = rs.RecordCount; if (page <= dd) { rs.absolutepage = page; var str = " "; var j = 0; while (!(rs.eof)) { if (j <= (new_pagesize() - 1)) { str = str + "<div align=/"left/">"; //str=str+ "<tr><Td align=/"left/">" str = str + "<img src="/" mce_src="/""images/memo.gif/" border=/"0/" /> "; str = str + "<a href="/" mce_href="/""page_detail.asp?id=" + rs("id") + "/">" + rs("title") + "</a>"; str = str + "<div styele=/"margin:10px;/"> </div>"; //str=str+ "</td></tr>" str=str+ ("</div>"); } j = j + 1; rs.movenext; } pagepage.innerHTML = str; //输出分页导航 var str2 = ""; var onclickk = "<a href="###" mce_href="###" onclick='list('"; for (var i = 1; i <= dd; i++) { str2 = str2 + "<a href="###" mce_href="###" onclick='list(" + i + ");'>" + i + "</a> "; } s_page.innerHTML = str2; total_page.innerText = dd; total_page.title = dd; //插入总页数 document.getElementById("pageno").value = page; var obj_curr_page = document.getElementById("curr_page"); obj_curr_page.innerHTML = page; var obj_total_record = document.getElementById("total_record"); obj_total_record.innerHTML = rc; loadxml(); //读取配置文件 var news_pagesize = root.selectSingleNode("//Page/new_pagesize").firstChild.nodeValue; var obj_news_pagesize = document.getElementById("news_pagesize"); obj_news_pagesize.innerHTML = news_pagesize; } else { alert("数据不够,总共才" + dd + "页"); } } catch (e) { list1(1) } } function move_last() { var obj_total_page = document.getElementById("total_page").title; list1(obj_total_page); } function list1(page) { //缓冲区设计 避免LOAD页面时XML数据还没到来 var sss = $("Detailsdso"); //alert(sss.readyState) if (sss.src == "") { sss.src = xml_file; } //将LOAD文件归入JS控制 以便检测状况 if (sss.readyState == "complete") { list(page); } else { var loading = $("loading"); var bigclass = $("bigclass"); //there's problem :Select alway over the DIV... bigclass.style.display = "none"; loading.style.display = "block"; Effect.Pulsate("loading"); loading.style.left = Math.floor(window.screen.width / 3); //居中 loading.style.top = Math.floor(window.screen.height / 3); //alert(loading.style) setTimeout("list(" + page + ")", 1000); //re-loading time 根据网速设置时间不同 } } function _goto() { if (checkNum(document.getElementById("pageno").value)) { list1(Math.floor(document.getElementById("pageno").value)) } else { document.getElementById("pageno").value = 1 } } function checkNum(str) { return !//D/.test(str) } //检查是否数字组成 function new_pagesize() { loadxml(); var new_pagesize = root.selectSingleNode("//Page/new_pagesize").firstChild.nodeValue; //var obj_new_pagesize = document.getElementById("new_pagesize"); //obj_new_pagesize.innerText = new_pagesize; return new_pagesize = new_pagesize; //alert(new_pagesize); } function ContentSize(size)//文章字体调整 { var obj = $("main_content"); obj.style.fontSize = size + "px"; } function ch_dl(selObj, restore) { //reload & RE SQL//alert("s");//出现同步问题 ,可在缓冲区里解决 var objXML3 = document.getElementById("Detailsdso"); objXML3.src = xml_file + "?s1=" + selObj.options[selObj.selectedIndex].value; list1(1); if (restore) { selObj.selectedIndex = 0; } }

记得早期把玩 yui-ext 时候,曾经给一个函数折腾得几度想放弃 yui-ext。所说的那个函数就是就是 onReady

    /* 
     * 注册浏览器的DOMContentLoaded事件,@todo 有自我卸载的功能。 
     * @param { Function } onready [必填]在DOMContentLoaded事件触发时需要执行的函数 
     */  
    function onReady(onready){  
            var isReady = false;  
            function doReady(){  
                    if( isReady ) return;  
                    //确保onready只执行一次  
                    isReady = true;  
                    onready();  
            }  
            if(window.navigator.isIE8){/*IE*/  
                    (function(){  
                            if ( isReady ) return;  
                            try{  
                                    document.documentElement.doScroll("left");  
                            }catch( error ) {  
                                    setTimeout( arguments.callee, 0 );  
                                    return;  
                            }  
                            doReady();  
                    })();  
                    //window.attachEvent('onload',doReady);  
            }else if (window.navigator.isWebkit && window.navigator.webkitVersion < 525){/*Webkit*/  
                    (function(){  
                            if(isReady) return;  
                            if (/loaded|complete/.test(document.readyState)){  
                                    doReady();  
                            }else{  
                                    setTimeout( arguments.callee, 0 );  
                            }  
                    })();  
                    //window.addEventListener('load',doReady,false);  
            }else{                                                                /*FF Opera 高版webkit 其他*/  
                    document.addEventListener("DOMContentLoaded", doReady, false);  
                    //document.removeEventListener( "DOMContentLoaded", arguments.callee, false );  
            }  
    }  

精简版:

function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}  

http://js8.in/682.html#0-tsina-1-29606-397232819ff9a47a7b7e80a40613cfe1
http://dustindiaz.com/smallest-domready-ever

跨组件使用WSC组件对象

WSC 组件就是微软平台上脚本的模块化。在笔者的实践过程中,研究出一套灵活传递对象的方法,其实质就是送入 host.eval 函数的引用。见下面的 WSC 组件例子:

<?xml version="1.0" encoding="UTF-8"?>
<package>
	<component id="deepcms">
		<?component error="true" debug="true"?>
		<implements type="ASP" id="ASP" />
		<registration progid="deepcms" />
		<public>
			<method name="getEdk" />
			<method name="getExtDirect" />
			<method name="getDeepBlog" />
			<method name="getDeepCMS" />
			<method name="domain">
				<PARAMETER name="ns" />
			</method>
		</public>
		<script type="text/javascript">
			with(new ActiveXObject('package_loader')){
				init({
					 evalFn     : eval
					,edk_folder : 'd:/projects/edk'
				});
				_import('core');
				_import('asp');
				var folder = Application.Contents('edk_root');
				var entity = Server.mappath('/app/deepcms/service/entity.js');
				_import(null, entity);
				var page = Server.mappath('/app/deepcms/service/page.js');
				_import(null, page);
				var deepcms_config = Server.mappath('/app/app/config/config.js');
				_import(null, deepcms_config);
				var deepcms_news = Server.mappath('/app/app/news/news.js');
				_import(null, deepcms_news);
				var deepcms_user = Server.mappath('/app/app/user/user.js');
				_import(null, deepcms_user);
			}
			function getEdk(){
				return $;
			}
			function getExtDirect(){
				return Ext.direct;
			}
			function getDeepBlog(){
				return DeepBlog;
			}
			function domain(ns){
				return $.Model.init.call(eval(ns));
			}
			function getDeepCMS(){
				return DeepCMS;
			}
	</script>
	</component>
</package>

通过GetObject()调用:

// D:/dev/new/news/news.wsc
$$ = GetObject("script:" + Server.mappath('/libs/edk/edk-server/edk.wsc').replace(/\\/g, '/')).getEdk();

附送一个小脚本,有时很有用。

var wshObj = new ActiveXObject("WScript.Shell");
var code = wshObj.run('testServer fileServer.js', 0/*  不显示GUI,后台运行 */, false /*不等待程序,也就是执行之后就好*/);
alert('已启动node服务器!\n运行代码' + code);
close();

WScript.Shell 常用命令

WScript = {
	/**
	 * 不显示UI,以后台执行的方式运行程序。
	 * @param	{String} cmd
	 * @return	{Number}
	 */
	quietRun : function (cmd){
		var wshObj = new ActiveXObject("WScript.Shell");
	    return wshObj.run(cmd, 0/*  不显示GUI,后台运行 */, false /*不等待程序,也就是执行之后就好*/);
	}
	
	/**
	 * 目录选择器。
	 * @param 	{String}			str
	 * @return 	{Shell.Application}
	 */
	,showFolderPickuper : function (str){
	    var objFolder = new ActiveXObject("Shell.Application").BrowseForFolder(
	         0
	        ,str || "请选择一个目录。"
	        ,0
	        ,0x11
	    );
	    return objFolder ? objFolder.Self.Path : '';
	}
	
	/**
	 * 在脚本中创建浏览器窗体 适合WSC使用。
	 */
	,createBrowser : function (){
	    with(new ActiveXObject("InternetExplorer.Application")){
	        visible		=	false;
	        addressBar	=	false;
	        menuBar		=	false;
	        statusBar	=	false;
	        toolBar		=	false;
	        resizable	=	true;
	        left		=	300;
	        top			=	200;
	        width		=	300;
	        height		=	240;
	        silent		=	true;
	        navigate("http://localhost");
	        /*
	        Document.title="VBScript 创建的窗口";
	        Document.body.bgColor="#ECE9D8";
	        Document.body.style.overflow="hidden";
	        Document.body.style.borderWidth="0";
	        Document.body.innerHtml="hi  ";
	        */
	        visible		=	true;
	    }
	}
	
	/**
	 * 显示系统变量,包括"Process"、"User"和"System"。
	 * @return {Object}
	 */
	,showSystemVars : function (){
		var wshObj = new ActiveXObject("WScript.Shell");
	    var 
         args 	= ["Process", "User", "System"]
        ,result	= {}
        ,item
        ,e;
	        
	    for(var i = args.length-1; i >= 0; i--){
	        result[args[i]] = {};
	        for(e  = new Enumerator(wshObj.Environment(args[i])); !e.atEnd(); e.moveNext()){
	            var item = e.item().split("=");
	            result[args[i]][item[0]] = item[1];
	        }
	    }
	    
	    return result;
	}
		
	/**
	 * 添加系统环境变量。
	 * @param	{Sting} 	key
	 * @param	{String}	value
	 * @return	{String}
	 */
	,addEnvVar : function (key, value){
		var wshObj = new ActiveXObject("WScript.Shell");
	    var oSysEnv = wshObj.Environment("SYSTEM");
	    if(!oSysEnv(key) && oSysEnv(key).indexOf(value) == -1){
	        oSysEnv(key) = value;
	    }else{
	        alert(value + '已经在了');
	    }
	     
	    return oSysEnv(key);
	}
	
	/**
	 * 添加PATH环境变量
	 * @param {String} v 目录字符串
	 */
	,addPath : function (v){
		var wshObj  = new ActiveXObject("WScript.Shell");
	    var oSysEnv = wshObj.Environment("SYSTEM");
	    
	    if( oSysEnv("Path").indexOf(v) == -1){
	        oSysEnv("Path") += ';' + v;
	    }else{
	       alert('警告:该条目' + v +'已存在!');
	    }
	    return oSysEnv("Path");
	}
	
	/**
	 * 获取系统文件夹。通过字体目录获取的。
	 * @credit http://hi.baidu.com/ucren/blog/item/689d534e6ece2903b2de050f.html
	 */
	,getSpecialFolder: function(type){
	    var fontPath = shell.SpecialFolders("Fonts");
	    var winPath = fontPath.slice(0, fontPath.lastIndexOf("\\"));
	    switch(type){
	        case "windows":
	            return winPath;
	            break;
	        case "system32":
	            return winPath + "\\system32";
	            break;
	        default:
	            return shell.SpecialFolders(type);
	            break;
	    }
	}
};
上一篇:我的前端成长之路:中医药大学毕业的业务女前端修炼之路


下一篇:Operations Manager 2007 R2系列之审计日志安装