What are JavaScript modules? What is their purpose? - Definition: how to encapsulate a piece of code into a useful unit, and how to register its capability/export a value for the module. - Dependency References: how to refer to other units of code.
define(['use!underscore','use!backbone'],function(_,Backbone){varContact=Backbone.Model.extend({defaults:{name:'unamed',email:''},filter:function(query){//helper function for user searchif(typeof(query)==='undefined'||query===null||query==='')returntrue;query=query.toLowerCase();returnthis.get('name').toLowerCase().indexOf(query)!=-1||this.get('email').toLowerCase().indexOf(query)!=-1;}});returnContact;});
<header><aclass="save">Save</a><aclass="delete">Delete</a></header><divclass="content"><form><label><span>Name</span><inputtype="text"name="name"value="<%= name %>"></label><label><span>Email</span><inputtype="email"name="email"value="<%= email %>"></label><button>Save</button></form></div>
define(['jquery','use!underscore','use!backbone','views/show','views/edit'],function($,_,Backbone,showView,editView){// main view for show and viewvarMainView=Backbone.View.extend({className:'main stack',initialize:function(){this.editView=editView;this.showView=showView;},render:function(){this.$el.append(this.showView.render().el);this.$el.append(this.editView.render().el);returnthis;},edit:function(item){this.showView.$el.removeClass('active');this.editView.$el.addClass('active');this.editView.change(item);},show:function(item){this.editView.$el.removeClass('active');this.showView.$el.addClass('active');this.showView.change(item);}});returnnewMainView();});
define(['use!underscore','use!backbone',],function(_,Backbone){//Context to store global variable.// It also provides the pubsub service for other modules.varglobal={};_.extend(global,Backbone.Events);returnglobal;});
// Filename: store.jsdefine(['use!underscore','use!backbone'],function(_,Backbone){// A simple module to replace `Backbone.sync` with *localStorage*-based// persistence. Models are given GUIDS, and saved into a JSON object. Simple// as that.// Generate four random hex digits.functionS4(){return(((1+Math.random())*0x10000)|0).toString(16).substring(1);}// Generate a pseudo-GUID by concatenating random hexadecimal.functionguid(){return(S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());}// Our Store is represented by a single JS object in *localStorage*. Create it// with a meaningful name, like the name you'd give a table.varStore=function(name){this.name=name;varstore=localStorage.getItem(this.name);this.data=(store&&JSON.parse(store))||{};};_.extend(Store.prototype,{// Save the current state of the **Store** to *localStorage*.save:function(){localStorage.setItem(this.name,JSON.stringify(this.data));},// Add a model, giving it a (hopefully)-unique GUID, if it doesn't already// have an id of it's own.create:function(model){if(!model.id)model.id=model.attributes.id=guid();this.data[model.id]=model;this.save();returnmodel;},// Update a model by replacing its copy in `this.data`.update:function(model){this.data[model.id]=model;this.save();returnmodel;},// Retrieve a model from `this.data` by id.find:function(model){returnthis.data[model.id];},// Return the array of all models currently in storage.findAll:function(){return_.values(this.data);},// Delete a model from `this.data`, returning it.destroy:function(model){deletethis.data[model.id];this.save();returnmodel;}});// Override `Backbone.sync` to use delegate to the model or collection's// *localStorage* property, which should be an instance of `Store`.Backbone.sync=function(method,model,options){varresp;varstore=model.localStorage||model.collection.localStorage;switch(method){case"read":resp=model.id?store.find(model):store.findAll();break;case"create":resp=store.create(model);break;case"update":resp=store.update(model);break;case"delete":resp=store.destroy(model);break;}if(resp){options.success(resp);}else{options.error("Record not found");}};returnStore;});
// Filename: main.jsrequire(['app'],function(app){// The "app" dependency is passed in as "App"// Again, the other dependencies passed in are not "AMD" therefore don't pass a parameter to this functionapp.initialize();});
// Require.js allows us to configure shortcut alias// Their usage will become more apparent futher along in the tutorial.require.config({// Initialize the application with the main application filedeps:["main"],paths:{// JavaScript folderslibs:"libs",// Librariesjquery:'libs/jquery/1.7.2/jquery',underscore:'libs/underscore/1.3.2/underscore',backbone:'libs/backbone/0.9.2/backbone',// requirejs pluginstext:'libs/require/plugins/text',use:'libs/require/plugins/use',order:'libs/require/plugins/order',//templatetemplates:'../templates'},use:{backbone:{deps:["use!underscore","jquery"],attach:"Backbone"},underscore:{attach:"_"}}});