Documentos de Académico
Documentos de Profesional
Documentos de Cultura
js
TomadodeStackOverflowyTuts
Backbone.jsgivesstructuretowebapplicationsbyprovidingmodelswithkeyvaluebindingand
customevents,collectionswitharichAPIofenumerablefunctions,viewswithdeclarative
eventhandling,andconnectsitalltoyourexistingAPIoveraRESTfulJSONinterface.
Backboneisasuperlightweightlibrarythatletsyoucreateeasytomaintainfrontends.It's
backendagnosticandworkswellwithanyofthemodernJavaScriptlibrariesyou'realready
using.
Key-value binding and custom events
Whenamodel'scontentsorstateischanged,otherobjectsthathavesubscribedtothemodel
arenotifiedsotheycanproceedaccordingly.Here,theviewslistentochangesinthemodel,and
updatethemselvesaccordinglyinsteadofthemodelhavingtodealwiththeviewsmanually.
Rich API of enumerable functions
Backboneshipswithanumberofveryusefulfunctionsforhandlingandworkingwithyourdata.
Unlikeotherimplementation,arraysinJavaScriptareprettyneutered,whichreallyisa
hamperingproblemwhenyouhavetodealwithdata.
Views with declarative event handling
Yourdaysofwritingspaghettibindcallsareover.Youcanprogrammaticallydeclarewhich
callbackneedstobeassociatedwithspecificelements.
RESTful JSON interface
EventhoughthedefaultmethodistouseastandardAJAXcallwhenyouwanttotalktothe
server,youcaneasilyswitchitouttoanythingyouneed.Anumberofadaptershavesprungup
coveringmostofthefavoritesincludingWebsocketsandlocalstorage.
Backboneprovidesacleanwaytosurgicallyseparateyourdatafromyourpresentation.The
modelthatworkswiththedataisonlyconcernedwithsynchronizingwithaserverwhiletheview's
primarydutyislisteningtochangestothesubscribedmodelandrenderingtheHTML.
Does it replace jQuery?
No.They'reprettycomplementaryintheirscopeswithalmostnooverlapsinfunctionality.
Backbonehandlesallthehigherlevelabstractions,whilejQueryorsimilarlibrariesworkwith
theDOM,normalizeeventsandsoon.
Theirscopesandusecasesareprettydifferentandbecauseyouknowonedoesn'tmeanthat
youshouldn'tlearntheother.AsaJavaScriptdeveloper,youshouldknowhowtoeffectivelywork
withboth.
Where should I be using this?
Backboneisideallysuitedforcreatingfrontendheavy,datadrivenapplications.ThinktheGMail
interface,newTwitteroranyotherrevelationofthepastfewyears.Itmakescreatingcomplex
appseasier.
Whileyoucanshoehornitformoremainstreamwebpages,thisisreallyalibrarythatistailored
forwebapps.
I can still use other libraries on the page, right?
Absolutely.NotonlyyourtypicalDOMaccessing,AJAXwrappingkind,butalsotherestofyour
templatingandscriptloadingkind.It'svery,verylooselycoupled,whichmeansyoucanuse
almostallofyourtoolsinconjunctionwithBackbone.
Backbone.jsisbasicallyanuberlightframeworkthatallowsyoutostructureyourJavascript
codeinanMVC(Model,View,Controller)fashionwhere...
Modelispartofyourcodethatretrievesandpopulatesthedata,
ViewistheHTMLrepresentationofthismodel(viewschangeasmodelschange,etc)
andControllerthatinthiscaseallowsyoutosavethestateofyourjavascriptapplicationviaa
hashbangurl,forexample:http://twitter.com/#search?q=backbone.js
SomeprosthatIdiscoveredwithBackbone:
NomoreJavascriptSpaghetti:codeisorganizedandbrokendownintosemantically
meaningful.jsfileswhicharelatercombinedusingJAMMIT
NomorejQuery.data(bla,bla):noneedtostoredatainDOM,storedatainmodels
instead
eventbindingjustworks
extremelyusefulunderscoreutilitylibrary
backbone.jscodeiswelldocumentedandagreatread.openedmyeyestoanumberof
JScodetechniques.
Cons:
Tookmeawhiletowrapmyheadarounditandfigureouthowtoapplyittomycode,but
imaJavascriptNewb.
2.
Ifyou'regoingtobuildcomplexuserinterfacesinthebrowserthenyouwillprobablyfindyourself
eventuallyinventingmostofthepiecesthatmakeupframeworkslikeBackbone.jsand
Sammy.js.Sothequestionis,areyoubuildingsomethingcomplicatedenoughinthebrowserto
meritusingit(soyoudon'tendupinventingthesamethingyourself).
IfwhatyouplantobuildissomethingwheretheUIregularlychangeshowitdisplaysbutdoes
notgototheservertogetentirenewpagesthenyouprobablyneedsomethinglike
Backbone.jsorSammy.js.ThecardinalexampleofsomethinglikethatisGoogle'sGMail.If
you'veeverusedityou'llnoticethatitdownloadsonebigchunkofHTML,CSS,andJavaScript
whenyoufirstloginandthenafterthateverythinghappensinthebackground.Itcanmove
betweenreadinganemailandprocessingtheinboxandsearchingandbackthroughallofthem
againwithouteveraskingforawholenewpagetoberendered.
It'sthatkindofappthattheseframeworksexcelatmakingeasiertodevelop.Withoutthemyou'll
eitherendupglommingtogetheradiversesetofindividuallibrariestogetpartsofthe
functionality(forexample,jQueryBBQforhistorymanagement,Events.jsforevents,etc.)or
you'llendupbuildingeverythingyourselfandhavingtomaintainandtesteverythingyourselfas
well.ContrastthatwithsomethinglikeBackbone.jsthathasthousandsofpeoplewatchingiton
Github,hundredsofforkswherepeoplemaybeworkingonit,andhundredsofquestionsalready
askedandansweredhereonStackOverflow.
Butnoneofitisofanyimportanceifwhatyouplantobuildisnotcomplicatedenoughtobeworth
thelearningcurveassociatedwithaframework.Ifyou'restillbuildingPHP,Java,orsomething
elsesiteswherethebackendserverisstilldoingalltheheavyliftingofbuildingthewebpages
uponrequestbytheuserandJavaScript/jQueryisjusticinguponthatprocess,youaren'tgoing
toneedorarenotyetreadyforBackbone.js.
Core
Backbone'scoreconsistsoffourmajorclasses:
Model
Collection
View
Controller
Model
ModelscanmeandifferentthingsindifferentimplementationsofMVC.InBackbone,amodel
representsasingularentityarecordinadatabaseifyouwill.Buttherearenohardandfast
ruleshere.
ModelsaretheheartofanyJavaScriptapplication,containingtheinteractivedataaswellasa
largepartofthelogicsurroundingit:conversions,validations,computedproperties,andaccess
control.
Example
varGame=Backbone.Model.extend({})
varGame=Backbone.Model.extend({
initialize:function(){
alert("Ohhey!")
},
defaults:{
name:'Defaulttitle',
releaseDate:2011,
}
})
Collection
CollectionsinBackboneareessentiallyjustacollectionofmodels.Goingwithourdatabase
analogyfromearlier,collectionsaretheresultsofaquerywheretheresultsconsistsofa
numberofrecords[models].Youcandefineacollectionlikeso:
varGamesCollection=Backbone.Collection.extend({
model:Game,
}
})
View
Aviewhandlestwodutiesfundamentally:
ListentoeventsthrownbytheDOMandmodels/collections.
Representtheapplication'sstateanddatamodeltotheuser.
GameView=Backbone.View.extend({
tagName:"div",
className:"game",
render:function(){
//codeforrenderingtheHTMLfortheview
}
})
Controller
ControllersinBackboneessentiallyletyoucreatebookmarkable,statefulappsbyusing
hashbangs.
varHashbangs=Backbone.Controller.extend({
routes:{
"!/": "root",
"!/games": "games",
},
root:function(){
//Prepthehomepageandrenderstuff
},
games:function(){
//Rerenderviewstoshowacollectionofbooks
},
})
Enlaces
WeboficialdeBackbone.js:http://backbonejs.org/
Tutorialentuts:http://code.tutsplus.com/tutorials/gettingstartedwithbackbonejsnet19751
backboneandrails:
http://www.jamesyu.org/2011/01/27/cloudeditabackbonejstutorialbyexample/
backboneandrailspart2:
http://www.jamesyu.org/2011/02/09/backbone.jstutorialwithrailspart2/