前进的javascript库

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

AdvancingJavaScriptwithLibrariesJohnResigejohn.org/jquery.com/mozilla.comTwoHats•MozillaCorp•FUEL•JSLibforExt.Devs•ReduceComplexity•JSLibTestSuites•Integration,bettercoverage•jQueryJavaScriptLibrary•ReleasedJan2006•SmallFilesize•Short,concise,code•ExtensibleviapluginsLibrariesare...•...abstractionsawayfromexistingAPIs•...givingusnewAPIstointerfacewith•APIsbreedpatterns•LibrariesbuildnewpatternsontopofexistingAPIs•Newlibrarypatternsadvancedevelopmentinmeaningful,considerable,waysHypothesisWhyCreateALibrary?•Distanceourselvesfromrepetition•InJavaScript:•Distancefrombrowserdifferences•InC(stdlib):•DistancefromplatformdifferencesDOMAPI•Implementedineverymodernbrowser•MoststableofalltheJavaScriptAPIs•VerywelldocumentedFailsinIE7objectid=”obj”paramname=srcvalue=test.mov/paramname=titlevalue=MyVideo//objectHTML:JavaScript:document.getElementById(“obj”).getElementsByTagName(“*”)FailsinSafari2divstyle=”display:none;”selectoptionid=”opt”value=”test”//select/divHTML:JavaScript:document.getElementById(“opt”).selectedGenuineBugsFailsinOpera&IEformaction=method=POSTinputtype=textname=q/spanid=qSearch/span/formHTML:JavaScript:document.getElementById(“q”)FailsinOpera&IEformaction=method=POSTNumRows:inputtype=textid=lengthvalue=22/br/inputtype=submitvalue=Generate//formHTML:JavaScript:varf=document.getElementsByTagName(“input”);for(vari=0;if.length;i++){...}Re-interpretationoftheSpecFailsinAllinputtype=”text”id=”name”disabled=”disabled”/HTML:JavaScript:document.getElementById(“name”).setAttribute(“disabled”,false);FailsinAllbody.../bodyHTML:JavaScript:document.body.setAttribute(“class”,“home”);WhatyouexpectWhyareLibrariesCreated?•Browsershavealargenumberofstrangedifferences...•IEhasalotofwelldocumentedbugs•Safarihasless,butmoreobscure,bugs•APIsdon’tdowhatyouexpect•WhentheAPIisimpossibletolearn,butthroughexperienceBreakdownintoMeta-Problems•Waitingforthedocumenttoload•TraversingtheDOM•InjectingHTMLintoapageWaitingfortheDOMtoload•ADOMdocumentmustbefullyloadedbeforeyoucanworkwithit•Waitingforthewindowtoloadcausesflashesofun-effectedcontentFocusinganinputinputtype=”text”id=”test”/scriptdocument.getElementById(“test”).focus();/scriptheadscriptsrc=”script.js”/head$(document).ready(function(){$(“#test”).focus();});TraversingtheDOM•getElementsByTagName,getElementById,getAttribute,nextSibling,previousSibling,parentNode,className,etc.•Alottolearnandgetright•Hasthepotentialtobeverytricky(andlong-winded)DOMSelectors•Goal:ImprovetheDOMTraversalAPI•ProvideanAPIontopoftheexistingDOMAPI•LooktostandardsforinspirationTypesofSelectors•XPathSelectors•//div/span[2]•/html[@id=’home’]•CSS3Selectors•divspan:nth-of-type(2)•html:root#homeNon-trivialSelectors$(“#menuli:not(:first-child)”).hide();$(“ul[ul]”).show();$(“tr:even”).addClass(“even”);InjectingHTML•Veryfrustratingproblem•Browsersareverytempermental•(Insertingtablerows,selectoptions,etc.)HTMLSolution•AllowuserstoinsertHTMLstrings•ConverttoDOMnodesonthefly•Injectintothedocumentcorrectly$(“tabletr”).append(“tdtest/td”);$(“select”).prepend(“optiontest/option”);•DOMReady+Selectors+HTMLInjection•ThedreamoftrueunobtrusiveDOMscripting$(document).ready(function(){$(“select”).append(“optionNone/option”);});NewExpectations•WhatnewexpectationsemergeoutofthisnewAPI?$(“ulli”).click(function(){$(this).load(“menu.html”);});ulliitema/liliitemb/li/ulThePerception•Whenthedocumentwasready:•Weboundaneventtoasetofelements•Weloadedsomenewelements•Whydon’ttheyhavetheevent?NewPattern:BehaviorsfunctionhandleClick(){$(“li”,this).click(loadMenu);}functionloadMenu(){$(this).load(“menu.html”,handleClick);}$(document).ready(function(){$(document).each(handleClick);});Behaviors$(document).ready(function(){$(“li”).behavior(“click”,function(){$(this).load(“menu.html”);});});PureDOMfunctionhandleClick(elem){varli=elem.getElementsByTagName(“li”);for(vari=0;ili.length;i++)li[i].addEventListener(“click”,loadMenu,false);}functionloadMenu(){varelem=this;varxhr=newXMLHttpRequest();xhr.open(“GET”,“menu.html”,false);xhr.onreadystatechange=function(){if(xhr.readyState==4){elem.innerHTML=xhr.responseText;handleClick(elem);}};xhr.send(null);}window.onload=function(){varul=document.getElementsByTagName(“ul”);for(vari=0;iul.length;i++)handleClick(ul[i]);};Doesn’texistinIEIEsetsthewrongcontextDoesn’texistinIELeaksinIEDoesn’thappenimmediatelyFUEL•JavaScriptLibraryforFirefoxExtensionDevelopment•DesignedtobeusedbyWebDevelopers•CurrentAPIisveryC++centricMozilla:Preferencesvarprefs=Components.classes[@mozilla.org/preferences-service;1].getService(Components.interfaces.nsIPrefBranch);varstr=Components.classes[@mozilla.org/supports-string;1].createInstance(Components.interfaces.nsISupportsString);str.data=somenon-asciitext;prefs.setComplexValue(preference.with.non.ascii.value,Components.interfaces.nsISupportsString,str);Preferencesw/FUELApplication.prefs.setValue(“some.pref”,“somenon-asciitext”);SQLProgrammingLanguageInterfaceAbstractionLayer(ORM)SELECT*FROMusersWH

1 / 39
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功