├── Config.xml ├── bootstrap ├── css │ └── style.css └── js │ ├── bootstrap.min.js │ └── jquery.min.js ├── index.html └── js ├── underscore.js └── backbone.js /Config.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | Your Vote Counts 11 | 12 | 13 | Just election monitoring app 14 | 15 | 16 | 17 | Moe Hein Kyaw 18 | 19 | 20 | -------------------------------------------------------------------------------- /bootstrap/css/style.css: -------------------------------------------------------------------------------- 1 | 2 | * { 3 | -webkit-touch-callout: none; 4 | -webkit-text-size-adjust: none; 5 | -webkit-tap-highlight-color: rgba(0,0,0,0); 6 | -webkit-user-select: none; 7 | } 8 | 9 | body { 10 | -webkit-touch-callout: none; 11 | -webkit-text-size-adjust: none; 12 | -webkit-user-select: none; 13 | } 14 | 15 | label.form-label { 16 | font-size: 1.5em; 17 | font-weight: normal; 18 | } 19 | 20 | .btn { 21 | margin-top: 0.5em; 22 | } 23 | 24 | .btn.btn-lg.btn-fixed { 25 | /* width: 7em; 26 | */} 27 | 28 | .btn.btn-lg { 29 | margin-right: 1em; 30 | } 31 | 32 | .btn-bold { 33 | font-weight: bold; 34 | } 35 | 36 | fieldset { 37 | padding: 0.75em 0.5em; 38 | } 39 | 40 | .bg-grey { 41 | background-color: #ECF0F1; 42 | } 43 | 44 | .bg-grey-1 { 45 | background-color: #fff; 46 | } 47 | 48 | .container-fluid { 49 | margin: 0; 50 | } 51 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Your Vote Count 5 | 6 | 7 | 8 | 9 | 10 | 63 | 64 | 65 | 66 |
67 |
68 |
69 | 70 | 71 |
72 | 73 | 74 |
75 |
76 | 77 |
78 | 79 | 80 |
81 | 82 | 83 |
84 |
85 | 86 |
87 | 88 | 89 |
90 | 91 | 92 | 93 | 94 |
95 |
96 | 97 |
98 | 99 | 100 |
101 | 102 | 103 | 104 | 105 | 106 | 107 |
108 |
109 | 110 |
111 | 112 | 113 |
114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 |
124 |
125 | 126 |
127 | 128 | 129 |
130 | 131 | 132 |
133 |
134 | 135 | 136 | -------------------------------------------------------------------------------- /bootstrap/js/bootstrap.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Bootstrap v3.1.1 (http://getbootstrap.com) 3 | * Copyright 2011-2014 Twitter, Inc. 4 | * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) 5 | */ 6 | if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one(a.support.transition.end,function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b()})}(jQuery),+function(a){"use strict";var b='[data-dismiss="alert"]',c=function(c){a(c).on("click",b,this.close)};c.prototype.close=function(b){function c(){f.trigger("closed.bs.alert").remove()}var d=a(this),e=d.attr("data-target");e||(e=d.attr("href"),e=e&&e.replace(/.*(?=#[^\s]*$)/,""));var f=a(e);b&&b.preventDefault(),f.length||(f=d.hasClass("alert")?d:d.parent()),f.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one(a.support.transition.end,c).emulateTransitionEnd(150):c())};var d=a.fn.alert;a.fn.alert=function(b){return this.each(function(){var d=a(this),e=d.data("bs.alert");e||d.data("bs.alert",e=new c(this)),"string"==typeof b&&e[b].call(d)})},a.fn.alert.Constructor=c,a.fn.alert.noConflict=function(){return a.fn.alert=d,this},a(document).on("click.bs.alert.data-api",b,c.prototype.close)}(jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d),this.isLoading=!1};b.DEFAULTS={loadingText:"loading..."},b.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",f.resetText||d.data("resetText",d[e]()),d[e](f[b]||this.options[b]),setTimeout(a.proxy(function(){"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},b.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")&&(c.prop("checked")&&this.$element.hasClass("active")?a=!1:b.find(".active").removeClass("active")),a&&c.prop("checked",!this.$element.hasClass("active")).trigger("change")}a&&this.$element.toggleClass("active")};var c=a.fn.button;a.fn.button=function(c){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof c&&c;e||d.data("bs.button",e=new b(this,f)),"toggle"==c?e.toggle():c&&e.setState(c)})},a.fn.button.Constructor=b,a.fn.button.noConflict=function(){return a.fn.button=c,this},a(document).on("click.bs.button.data-api","[data-toggle^=button]",function(b){var c=a(b.target);c.hasClass("btn")||(c=c.closest(".btn")),c.button("toggle"),b.preventDefault()})}(jQuery),+function(a){"use strict";var b=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,"hover"==this.options.pause&&this.$element.on("mouseenter",a.proxy(this.pause,this)).on("mouseleave",a.proxy(this.cycle,this))};b.DEFAULTS={interval:5e3,pause:"hover",wrap:!0},b.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},b.prototype.getActiveIndex=function(){return this.$active=this.$element.find(".item.active"),this.$items=this.$active.parent().children(),this.$items.index(this.$active)},b.prototype.to=function(b){var c=this,d=this.getActiveIndex();return b>this.$items.length-1||0>b?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){c.to(b)}):d==b?this.pause().cycle():this.slide(b>d?"next":"prev",a(this.$items[b]))},b.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},b.prototype.next=function(){return this.sliding?void 0:this.slide("next")},b.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},b.prototype.slide=function(b,c){var d=this.$element.find(".item.active"),e=c||d[b](),f=this.interval,g="next"==b?"left":"right",h="next"==b?"first":"last",i=this;if(!e.length){if(!this.options.wrap)return;e=this.$element.find(".item")[h]()}if(e.hasClass("active"))return this.sliding=!1;var j=a.Event("slide.bs.carousel",{relatedTarget:e[0],direction:g});return this.$element.trigger(j),j.isDefaultPrevented()?void 0:(this.sliding=!0,f&&this.pause(),this.$indicators.length&&(this.$indicators.find(".active").removeClass("active"),this.$element.one("slid.bs.carousel",function(){var b=a(i.$indicators.children()[i.getActiveIndex()]);b&&b.addClass("active")})),a.support.transition&&this.$element.hasClass("slide")?(e.addClass(b),e[0].offsetWidth,d.addClass(g),e.addClass(g),d.one(a.support.transition.end,function(){e.removeClass([b,g].join(" ")).addClass("active"),d.removeClass(["active",g].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger("slid.bs.carousel")},0)}).emulateTransitionEnd(1e3*d.css("transition-duration").slice(0,-1))):(d.removeClass("active"),e.addClass("active"),this.sliding=!1,this.$element.trigger("slid.bs.carousel")),f&&this.cycle(),this)};var c=a.fn.carousel;a.fn.carousel=function(c){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},b.DEFAULTS,d.data(),"object"==typeof c&&c),g="string"==typeof c?c:f.slide;e||d.data("bs.carousel",e=new b(this,f)),"number"==typeof c?e.to(c):g?e[g]():f.interval&&e.pause().cycle()})},a.fn.carousel.Constructor=b,a.fn.carousel.noConflict=function(){return a.fn.carousel=c,this},a(document).on("click.bs.carousel.data-api","[data-slide], [data-slide-to]",function(b){var c,d=a(this),e=a(d.attr("data-target")||(c=d.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"")),f=a.extend({},e.data(),d.data()),g=d.attr("data-slide-to");g&&(f.interval=!1),e.carousel(f),(g=d.attr("data-slide-to"))&&e.data("bs.carousel").to(g),b.preventDefault()}),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var b=a(this);b.carousel(b.data())})})}(jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d),this.transitioning=null,this.options.parent&&(this.$parent=a(this.options.parent)),this.options.toggle&&this.toggle()};b.DEFAULTS={toggle:!0},b.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},b.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b=a.Event("show.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.$parent&&this.$parent.find("> .panel > .in");if(c&&c.length){var d=c.data("bs.collapse");if(d&&d.transitioning)return;c.collapse("hide"),d||c.data("bs.collapse",null)}var e=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[e](0),this.transitioning=1;var f=function(){this.$element.removeClass("collapsing").addClass("collapse in")[e]("auto"),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return f.call(this);var g=a.camelCase(["scroll",e].join("-"));this.$element.one(a.support.transition.end,a.proxy(f,this)).emulateTransitionEnd(350)[e](this.$element[0][g])}}},b.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"),this.transitioning=1;var d=function(){this.transitioning=0,this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse")};return a.support.transition?void this.$element[c](0).one(a.support.transition.end,a.proxy(d,this)).emulateTransitionEnd(350):d.call(this)}}},b.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};var c=a.fn.collapse;a.fn.collapse=function(c){return this.each(function(){var d=a(this),e=d.data("bs.collapse"),f=a.extend({},b.DEFAULTS,d.data(),"object"==typeof c&&c);!e&&f.toggle&&"show"==c&&(c=!c),e||d.data("bs.collapse",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.collapse.Constructor=b,a.fn.collapse.noConflict=function(){return a.fn.collapse=c,this},a(document).on("click.bs.collapse.data-api","[data-toggle=collapse]",function(b){var c,d=a(this),e=d.attr("data-target")||b.preventDefault()||(c=d.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,""),f=a(e),g=f.data("bs.collapse"),h=g?"toggle":d.data(),i=d.attr("data-parent"),j=i&&a(i);g&&g.transitioning||(j&&j.find('[data-toggle=collapse][data-parent="'+i+'"]').not(d).addClass("collapsed"),d[f.hasClass("in")?"addClass":"removeClass"]("collapsed")),f.collapse(h)})}(jQuery),+function(a){"use strict";function b(b){a(d).remove(),a(e).each(function(){var d=c(a(this)),e={relatedTarget:this};d.hasClass("open")&&(d.trigger(b=a.Event("hide.bs.dropdown",e)),b.isDefaultPrevented()||d.removeClass("open").trigger("hidden.bs.dropdown",e))})}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}var d=".dropdown-backdrop",e="[data-toggle=dropdown]",f=function(b){a(b).on("click.bs.dropdown",this.toggle)};f.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(''}),b.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),b.prototype.constructor=b,b.prototype.getDefaults=function(){return b.DEFAULTS},b.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content")[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},b.prototype.hasContent=function(){return this.getTitle()||this.getContent()},b.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},b.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},b.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var c=a.fn.popover;a.fn.popover=function(c){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof c&&c;(e||"destroy"!=c)&&(e||d.data("bs.popover",e=new b(this,f)),"string"==typeof c&&e[c]())})},a.fn.popover.Constructor=b,a.fn.popover.noConflict=function(){return a.fn.popover=c,this}}(jQuery),+function(a){"use strict";function b(c,d){var e,f=a.proxy(this.process,this);this.$element=a(a(c).is("body")?window:c),this.$body=a("body"),this.$scrollElement=this.$element.on("scroll.bs.scroll-spy.data-api",f),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||(e=a(c).attr("href"))&&e.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.offsets=a([]),this.targets=a([]),this.activeTarget=null,this.refresh(),this.process()}b.DEFAULTS={offset:10},b.prototype.refresh=function(){var b=this.$element[0]==window?"offset":"position";this.offsets=a([]),this.targets=a([]);{var c=this;this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[b]().top+(!a.isWindow(c.$scrollElement.get(0))&&c.$scrollElement.scrollTop()),e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){c.offsets.push(this[0]),c.targets.push(this[1])})}},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,d=c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(b>=d)return g!=(a=f.last()[0])&&this.activate(a);if(g&&b<=e[0])return g!=(a=f[0])&&this.activate(a);for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(!e[a+1]||b<=e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,a(this.selector).parentsUntil(this.options.target,".active").removeClass("active");var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")};var c=a.fn.scrollspy;a.fn.scrollspy=function(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=c,this},a(window).on("load",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);b.scrollspy(b.data())})})}(jQuery),+function(a){"use strict";var b=function(b){this.element=a(b)};b.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a")[0],f=a.Event("show.bs.tab",{relatedTarget:e});if(b.trigger(f),!f.isDefaultPrevented()){var g=a(d);this.activate(b.parent("li"),c),this.activate(g,g.parent(),function(){b.trigger({type:"shown.bs.tab",relatedTarget:e})})}}},b.prototype.activate=function(b,c,d){function e(){f.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),b.addClass("active"),g?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active"),d&&d()}var f=c.find("> .active"),g=d&&a.support.transition&&f.hasClass("fade");g?f.one(a.support.transition.end,e).emulateTransitionEnd(150):e(),f.removeClass("in")};var c=a.fn.tab;a.fn.tab=function(c){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new b(this)),"string"==typeof c&&e[c]()})},a.fn.tab.Constructor=b,a.fn.tab.noConflict=function(){return a.fn.tab=c,this},a(document).on("click.bs.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(b){b.preventDefault(),a(this).tab("show")})}(jQuery),+function(a){"use strict";var b=function(c,d){this.options=a.extend({},b.DEFAULTS,d),this.$window=a(window).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(c),this.affixed=this.unpin=this.pinnedOffset=null,this.checkPosition()};b.RESET="affix affix-top affix-bottom",b.DEFAULTS={offset:0},b.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(b.RESET).addClass("affix");var a=this.$window.scrollTop(),c=this.$element.offset();return this.pinnedOffset=c.top-a},b.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},b.prototype.checkPosition=function(){if(this.$element.is(":visible")){var c=a(document).height(),d=this.$window.scrollTop(),e=this.$element.offset(),f=this.options.offset,g=f.top,h=f.bottom;"top"==this.affixed&&(e.top+=d),"object"!=typeof f&&(h=g=f),"function"==typeof g&&(g=f.top(this.$element)),"function"==typeof h&&(h=f.bottom(this.$element));var i=null!=this.unpin&&d+this.unpin<=e.top?!1:null!=h&&e.top+this.$element.height()>=c-h?"bottom":null!=g&&g>=d?"top":!1;if(this.affixed!==i){this.unpin&&this.$element.css("top","");var j="affix"+(i?"-"+i:""),k=a.Event(j+".bs.affix");this.$element.trigger(k),k.isDefaultPrevented()||(this.affixed=i,this.unpin="bottom"==i?this.getPinnedOffset():null,this.$element.removeClass(b.RESET).addClass(j).trigger(a.Event(j.replace("affix","affixed"))),"bottom"==i&&this.$element.offset({top:c-h-this.$element.height()}))}}};var c=a.fn.affix;a.fn.affix=function(c){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof c&&c;e||d.data("bs.affix",e=new b(this,f)),"string"==typeof c&&e[c]()})},a.fn.affix.Constructor=b,a.fn.affix.noConflict=function(){return a.fn.affix=c,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var b=a(this),c=b.data();c.offset=c.offset||{},c.offsetBottom&&(c.offset.bottom=c.offsetBottom),c.offsetTop&&(c.offset.top=c.offsetTop),b.affix(c)})})}(jQuery); -------------------------------------------------------------------------------- /js/underscore.js: -------------------------------------------------------------------------------- 1 | // Underscore.js 1.6.0 2 | // http://underscorejs.org 3 | // (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors 4 | // Underscore may be freely distributed under the MIT license. 5 | 6 | (function() { 7 | 8 | // Baseline setup 9 | // -------------- 10 | 11 | // Establish the root object, `window` in the browser, or `exports` on the server. 12 | var root = this; 13 | 14 | // Save the previous value of the `_` variable. 15 | var previousUnderscore = root._; 16 | 17 | // Establish the object that gets returned to break out of a loop iteration. 18 | var breaker = {}; 19 | 20 | // Save bytes in the minified (but not gzipped) version: 21 | var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; 22 | 23 | // Create quick reference variables for speed access to core prototypes. 24 | var 25 | push = ArrayProto.push, 26 | slice = ArrayProto.slice, 27 | concat = ArrayProto.concat, 28 | toString = ObjProto.toString, 29 | hasOwnProperty = ObjProto.hasOwnProperty; 30 | 31 | // All **ECMAScript 5** native function implementations that we hope to use 32 | // are declared here. 33 | var 34 | nativeForEach = ArrayProto.forEach, 35 | nativeMap = ArrayProto.map, 36 | nativeReduce = ArrayProto.reduce, 37 | nativeReduceRight = ArrayProto.reduceRight, 38 | nativeFilter = ArrayProto.filter, 39 | nativeEvery = ArrayProto.every, 40 | nativeSome = ArrayProto.some, 41 | nativeIndexOf = ArrayProto.indexOf, 42 | nativeLastIndexOf = ArrayProto.lastIndexOf, 43 | nativeIsArray = Array.isArray, 44 | nativeKeys = Object.keys, 45 | nativeBind = FuncProto.bind; 46 | 47 | // Create a safe reference to the Underscore object for use below. 48 | var _ = function(obj) { 49 | if (obj instanceof _) return obj; 50 | if (!(this instanceof _)) return new _(obj); 51 | this._wrapped = obj; 52 | }; 53 | 54 | // Export the Underscore object for **Node.js**, with 55 | // backwards-compatibility for the old `require()` API. If we're in 56 | // the browser, add `_` as a global object via a string identifier, 57 | // for Closure Compiler "advanced" mode. 58 | if (typeof exports !== 'undefined') { 59 | if (typeof module !== 'undefined' && module.exports) { 60 | exports = module.exports = _; 61 | } 62 | exports._ = _; 63 | } else { 64 | root._ = _; 65 | } 66 | 67 | // Current version. 68 | _.VERSION = '1.6.0'; 69 | 70 | // Collection Functions 71 | // -------------------- 72 | 73 | // The cornerstone, an `each` implementation, aka `forEach`. 74 | // Handles objects with the built-in `forEach`, arrays, and raw objects. 75 | // Delegates to **ECMAScript 5**'s native `forEach` if available. 76 | var each = _.each = _.forEach = function(obj, iterator, context) { 77 | if (obj == null) return obj; 78 | if (nativeForEach && obj.forEach === nativeForEach) { 79 | obj.forEach(iterator, context); 80 | } else if (obj.length === +obj.length) { 81 | for (var i = 0, length = obj.length; i < length; i++) { 82 | if (iterator.call(context, obj[i], i, obj) === breaker) return; 83 | } 84 | } else { 85 | var keys = _.keys(obj); 86 | for (var i = 0, length = keys.length; i < length; i++) { 87 | if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return; 88 | } 89 | } 90 | return obj; 91 | }; 92 | 93 | // Return the results of applying the iterator to each element. 94 | // Delegates to **ECMAScript 5**'s native `map` if available. 95 | _.map = _.collect = function(obj, iterator, context) { 96 | var results = []; 97 | if (obj == null) return results; 98 | if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); 99 | each(obj, function(value, index, list) { 100 | results.push(iterator.call(context, value, index, list)); 101 | }); 102 | return results; 103 | }; 104 | 105 | var reduceError = 'Reduce of empty array with no initial value'; 106 | 107 | // **Reduce** builds up a single result from a list of values, aka `inject`, 108 | // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. 109 | _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { 110 | var initial = arguments.length > 2; 111 | if (obj == null) obj = []; 112 | if (nativeReduce && obj.reduce === nativeReduce) { 113 | if (context) iterator = _.bind(iterator, context); 114 | return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); 115 | } 116 | each(obj, function(value, index, list) { 117 | if (!initial) { 118 | memo = value; 119 | initial = true; 120 | } else { 121 | memo = iterator.call(context, memo, value, index, list); 122 | } 123 | }); 124 | if (!initial) throw new TypeError(reduceError); 125 | return memo; 126 | }; 127 | 128 | // The right-associative version of reduce, also known as `foldr`. 129 | // Delegates to **ECMAScript 5**'s native `reduceRight` if available. 130 | _.reduceRight = _.foldr = function(obj, iterator, memo, context) { 131 | var initial = arguments.length > 2; 132 | if (obj == null) obj = []; 133 | if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { 134 | if (context) iterator = _.bind(iterator, context); 135 | return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); 136 | } 137 | var length = obj.length; 138 | if (length !== +length) { 139 | var keys = _.keys(obj); 140 | length = keys.length; 141 | } 142 | each(obj, function(value, index, list) { 143 | index = keys ? keys[--length] : --length; 144 | if (!initial) { 145 | memo = obj[index]; 146 | initial = true; 147 | } else { 148 | memo = iterator.call(context, memo, obj[index], index, list); 149 | } 150 | }); 151 | if (!initial) throw new TypeError(reduceError); 152 | return memo; 153 | }; 154 | 155 | // Return the first value which passes a truth test. Aliased as `detect`. 156 | _.find = _.detect = function(obj, predicate, context) { 157 | var result; 158 | any(obj, function(value, index, list) { 159 | if (predicate.call(context, value, index, list)) { 160 | result = value; 161 | return true; 162 | } 163 | }); 164 | return result; 165 | }; 166 | 167 | // Return all the elements that pass a truth test. 168 | // Delegates to **ECMAScript 5**'s native `filter` if available. 169 | // Aliased as `select`. 170 | _.filter = _.select = function(obj, predicate, context) { 171 | var results = []; 172 | if (obj == null) return results; 173 | if (nativeFilter && obj.filter === nativeFilter) return obj.filter(predicate, context); 174 | each(obj, function(value, index, list) { 175 | if (predicate.call(context, value, index, list)) results.push(value); 176 | }); 177 | return results; 178 | }; 179 | 180 | // Return all the elements for which a truth test fails. 181 | _.reject = function(obj, predicate, context) { 182 | return _.filter(obj, function(value, index, list) { 183 | return !predicate.call(context, value, index, list); 184 | }, context); 185 | }; 186 | 187 | // Determine whether all of the elements match a truth test. 188 | // Delegates to **ECMAScript 5**'s native `every` if available. 189 | // Aliased as `all`. 190 | _.every = _.all = function(obj, predicate, context) { 191 | predicate || (predicate = _.identity); 192 | var result = true; 193 | if (obj == null) return result; 194 | if (nativeEvery && obj.every === nativeEvery) return obj.every(predicate, context); 195 | each(obj, function(value, index, list) { 196 | if (!(result = result && predicate.call(context, value, index, list))) return breaker; 197 | }); 198 | return !!result; 199 | }; 200 | 201 | // Determine if at least one element in the object matches a truth test. 202 | // Delegates to **ECMAScript 5**'s native `some` if available. 203 | // Aliased as `any`. 204 | var any = _.some = _.any = function(obj, predicate, context) { 205 | predicate || (predicate = _.identity); 206 | var result = false; 207 | if (obj == null) return result; 208 | if (nativeSome && obj.some === nativeSome) return obj.some(predicate, context); 209 | each(obj, function(value, index, list) { 210 | if (result || (result = predicate.call(context, value, index, list))) return breaker; 211 | }); 212 | return !!result; 213 | }; 214 | 215 | // Determine if the array or object contains a given value (using `===`). 216 | // Aliased as `include`. 217 | _.contains = _.include = function(obj, target) { 218 | if (obj == null) return false; 219 | if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; 220 | return any(obj, function(value) { 221 | return value === target; 222 | }); 223 | }; 224 | 225 | // Invoke a method (with arguments) on every item in a collection. 226 | _.invoke = function(obj, method) { 227 | var args = slice.call(arguments, 2); 228 | var isFunc = _.isFunction(method); 229 | return _.map(obj, function(value) { 230 | return (isFunc ? method : value[method]).apply(value, args); 231 | }); 232 | }; 233 | 234 | // Convenience version of a common use case of `map`: fetching a property. 235 | _.pluck = function(obj, key) { 236 | return _.map(obj, _.property(key)); 237 | }; 238 | 239 | // Convenience version of a common use case of `filter`: selecting only objects 240 | // containing specific `key:value` pairs. 241 | _.where = function(obj, attrs) { 242 | return _.filter(obj, _.matches(attrs)); 243 | }; 244 | 245 | // Convenience version of a common use case of `find`: getting the first object 246 | // containing specific `key:value` pairs. 247 | _.findWhere = function(obj, attrs) { 248 | return _.find(obj, _.matches(attrs)); 249 | }; 250 | 251 | // Return the maximum element or (element-based computation). 252 | // Can't optimize arrays of integers longer than 65,535 elements. 253 | // See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797) 254 | _.max = function(obj, iterator, context) { 255 | if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { 256 | return Math.max.apply(Math, obj); 257 | } 258 | var result = -Infinity, lastComputed = -Infinity; 259 | each(obj, function(value, index, list) { 260 | var computed = iterator ? iterator.call(context, value, index, list) : value; 261 | if (computed > lastComputed) { 262 | result = value; 263 | lastComputed = computed; 264 | } 265 | }); 266 | return result; 267 | }; 268 | 269 | // Return the minimum element (or element-based computation). 270 | _.min = function(obj, iterator, context) { 271 | if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { 272 | return Math.min.apply(Math, obj); 273 | } 274 | var result = Infinity, lastComputed = Infinity; 275 | each(obj, function(value, index, list) { 276 | var computed = iterator ? iterator.call(context, value, index, list) : value; 277 | if (computed < lastComputed) { 278 | result = value; 279 | lastComputed = computed; 280 | } 281 | }); 282 | return result; 283 | }; 284 | 285 | // Shuffle an array, using the modern version of the 286 | // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). 287 | _.shuffle = function(obj) { 288 | var rand; 289 | var index = 0; 290 | var shuffled = []; 291 | each(obj, function(value) { 292 | rand = _.random(index++); 293 | shuffled[index - 1] = shuffled[rand]; 294 | shuffled[rand] = value; 295 | }); 296 | return shuffled; 297 | }; 298 | 299 | // Sample **n** random values from a collection. 300 | // If **n** is not specified, returns a single random element. 301 | // The internal `guard` argument allows it to work with `map`. 302 | _.sample = function(obj, n, guard) { 303 | if (n == null || guard) { 304 | if (obj.length !== +obj.length) obj = _.values(obj); 305 | return obj[_.random(obj.length - 1)]; 306 | } 307 | return _.shuffle(obj).slice(0, Math.max(0, n)); 308 | }; 309 | 310 | // An internal function to generate lookup iterators. 311 | var lookupIterator = function(value) { 312 | if (value == null) return _.identity; 313 | if (_.isFunction(value)) return value; 314 | return _.property(value); 315 | }; 316 | 317 | // Sort the object's values by a criterion produced by an iterator. 318 | _.sortBy = function(obj, iterator, context) { 319 | iterator = lookupIterator(iterator); 320 | return _.pluck(_.map(obj, function(value, index, list) { 321 | return { 322 | value: value, 323 | index: index, 324 | criteria: iterator.call(context, value, index, list) 325 | }; 326 | }).sort(function(left, right) { 327 | var a = left.criteria; 328 | var b = right.criteria; 329 | if (a !== b) { 330 | if (a > b || a === void 0) return 1; 331 | if (a < b || b === void 0) return -1; 332 | } 333 | return left.index - right.index; 334 | }), 'value'); 335 | }; 336 | 337 | // An internal function used for aggregate "group by" operations. 338 | var group = function(behavior) { 339 | return function(obj, iterator, context) { 340 | var result = {}; 341 | iterator = lookupIterator(iterator); 342 | each(obj, function(value, index) { 343 | var key = iterator.call(context, value, index, obj); 344 | behavior(result, key, value); 345 | }); 346 | return result; 347 | }; 348 | }; 349 | 350 | // Groups the object's values by a criterion. Pass either a string attribute 351 | // to group by, or a function that returns the criterion. 352 | _.groupBy = group(function(result, key, value) { 353 | _.has(result, key) ? result[key].push(value) : result[key] = [value]; 354 | }); 355 | 356 | // Indexes the object's values by a criterion, similar to `groupBy`, but for 357 | // when you know that your index values will be unique. 358 | _.indexBy = group(function(result, key, value) { 359 | result[key] = value; 360 | }); 361 | 362 | // Counts instances of an object that group by a certain criterion. Pass 363 | // either a string attribute to count by, or a function that returns the 364 | // criterion. 365 | _.countBy = group(function(result, key) { 366 | _.has(result, key) ? result[key]++ : result[key] = 1; 367 | }); 368 | 369 | // Use a comparator function to figure out the smallest index at which 370 | // an object should be inserted so as to maintain order. Uses binary search. 371 | _.sortedIndex = function(array, obj, iterator, context) { 372 | iterator = lookupIterator(iterator); 373 | var value = iterator.call(context, obj); 374 | var low = 0, high = array.length; 375 | while (low < high) { 376 | var mid = (low + high) >>> 1; 377 | iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; 378 | } 379 | return low; 380 | }; 381 | 382 | // Safely create a real, live array from anything iterable. 383 | _.toArray = function(obj) { 384 | if (!obj) return []; 385 | if (_.isArray(obj)) return slice.call(obj); 386 | if (obj.length === +obj.length) return _.map(obj, _.identity); 387 | return _.values(obj); 388 | }; 389 | 390 | // Return the number of elements in an object. 391 | _.size = function(obj) { 392 | if (obj == null) return 0; 393 | return (obj.length === +obj.length) ? obj.length : _.keys(obj).length; 394 | }; 395 | 396 | // Array Functions 397 | // --------------- 398 | 399 | // Get the first element of an array. Passing **n** will return the first N 400 | // values in the array. Aliased as `head` and `take`. The **guard** check 401 | // allows it to work with `_.map`. 402 | _.first = _.head = _.take = function(array, n, guard) { 403 | if (array == null) return void 0; 404 | if ((n == null) || guard) return array[0]; 405 | if (n < 0) return []; 406 | return slice.call(array, 0, n); 407 | }; 408 | 409 | // Returns everything but the last entry of the array. Especially useful on 410 | // the arguments object. Passing **n** will return all the values in 411 | // the array, excluding the last N. The **guard** check allows it to work with 412 | // `_.map`. 413 | _.initial = function(array, n, guard) { 414 | return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); 415 | }; 416 | 417 | // Get the last element of an array. Passing **n** will return the last N 418 | // values in the array. The **guard** check allows it to work with `_.map`. 419 | _.last = function(array, n, guard) { 420 | if (array == null) return void 0; 421 | if ((n == null) || guard) return array[array.length - 1]; 422 | return slice.call(array, Math.max(array.length - n, 0)); 423 | }; 424 | 425 | // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. 426 | // Especially useful on the arguments object. Passing an **n** will return 427 | // the rest N values in the array. The **guard** 428 | // check allows it to work with `_.map`. 429 | _.rest = _.tail = _.drop = function(array, n, guard) { 430 | return slice.call(array, (n == null) || guard ? 1 : n); 431 | }; 432 | 433 | // Trim out all falsy values from an array. 434 | _.compact = function(array) { 435 | return _.filter(array, _.identity); 436 | }; 437 | 438 | // Internal implementation of a recursive `flatten` function. 439 | var flatten = function(input, shallow, output) { 440 | if (shallow && _.every(input, _.isArray)) { 441 | return concat.apply(output, input); 442 | } 443 | each(input, function(value) { 444 | if (_.isArray(value) || _.isArguments(value)) { 445 | shallow ? push.apply(output, value) : flatten(value, shallow, output); 446 | } else { 447 | output.push(value); 448 | } 449 | }); 450 | return output; 451 | }; 452 | 453 | // Flatten out an array, either recursively (by default), or just one level. 454 | _.flatten = function(array, shallow) { 455 | return flatten(array, shallow, []); 456 | }; 457 | 458 | // Return a version of the array that does not contain the specified value(s). 459 | _.without = function(array) { 460 | return _.difference(array, slice.call(arguments, 1)); 461 | }; 462 | 463 | // Split an array into two arrays: one whose elements all satisfy the given 464 | // predicate, and one whose elements all do not satisfy the predicate. 465 | _.partition = function(array, predicate, context) { 466 | predicate = lookupIterator(predicate); 467 | var pass = [], fail = []; 468 | each(array, function(elem) { 469 | (predicate.call(context, elem) ? pass : fail).push(elem); 470 | }); 471 | return [pass, fail]; 472 | }; 473 | 474 | // Produce a duplicate-free version of the array. If the array has already 475 | // been sorted, you have the option of using a faster algorithm. 476 | // Aliased as `unique`. 477 | _.uniq = _.unique = function(array, isSorted, iterator, context) { 478 | if (_.isFunction(isSorted)) { 479 | context = iterator; 480 | iterator = isSorted; 481 | isSorted = false; 482 | } 483 | var initial = iterator ? _.map(array, iterator, context) : array; 484 | var results = []; 485 | var seen = []; 486 | each(initial, function(value, index) { 487 | if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { 488 | seen.push(value); 489 | results.push(array[index]); 490 | } 491 | }); 492 | return results; 493 | }; 494 | 495 | // Produce an array that contains the union: each distinct element from all of 496 | // the passed-in arrays. 497 | _.union = function() { 498 | return _.uniq(_.flatten(arguments, true)); 499 | }; 500 | 501 | // Produce an array that contains every item shared between all the 502 | // passed-in arrays. 503 | _.intersection = function(array) { 504 | var rest = slice.call(arguments, 1); 505 | return _.filter(_.uniq(array), function(item) { 506 | return _.every(rest, function(other) { 507 | return _.contains(other, item); 508 | }); 509 | }); 510 | }; 511 | 512 | // Take the difference between one array and a number of other arrays. 513 | // Only the elements present in just the first array will remain. 514 | _.difference = function(array) { 515 | var rest = concat.apply(ArrayProto, slice.call(arguments, 1)); 516 | return _.filter(array, function(value){ return !_.contains(rest, value); }); 517 | }; 518 | 519 | // Zip together multiple lists into a single array -- elements that share 520 | // an index go together. 521 | _.zip = function() { 522 | var length = _.max(_.pluck(arguments, 'length').concat(0)); 523 | var results = new Array(length); 524 | for (var i = 0; i < length; i++) { 525 | results[i] = _.pluck(arguments, '' + i); 526 | } 527 | return results; 528 | }; 529 | 530 | // Converts lists into objects. Pass either a single array of `[key, value]` 531 | // pairs, or two parallel arrays of the same length -- one of keys, and one of 532 | // the corresponding values. 533 | _.object = function(list, values) { 534 | if (list == null) return {}; 535 | var result = {}; 536 | for (var i = 0, length = list.length; i < length; i++) { 537 | if (values) { 538 | result[list[i]] = values[i]; 539 | } else { 540 | result[list[i][0]] = list[i][1]; 541 | } 542 | } 543 | return result; 544 | }; 545 | 546 | // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), 547 | // we need this function. Return the position of the first occurrence of an 548 | // item in an array, or -1 if the item is not included in the array. 549 | // Delegates to **ECMAScript 5**'s native `indexOf` if available. 550 | // If the array is large and already in sort order, pass `true` 551 | // for **isSorted** to use binary search. 552 | _.indexOf = function(array, item, isSorted) { 553 | if (array == null) return -1; 554 | var i = 0, length = array.length; 555 | if (isSorted) { 556 | if (typeof isSorted == 'number') { 557 | i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted); 558 | } else { 559 | i = _.sortedIndex(array, item); 560 | return array[i] === item ? i : -1; 561 | } 562 | } 563 | if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); 564 | for (; i < length; i++) if (array[i] === item) return i; 565 | return -1; 566 | }; 567 | 568 | // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. 569 | _.lastIndexOf = function(array, item, from) { 570 | if (array == null) return -1; 571 | var hasIndex = from != null; 572 | if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { 573 | return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); 574 | } 575 | var i = (hasIndex ? from : array.length); 576 | while (i--) if (array[i] === item) return i; 577 | return -1; 578 | }; 579 | 580 | // Generate an integer Array containing an arithmetic progression. A port of 581 | // the native Python `range()` function. See 582 | // [the Python documentation](http://docs.python.org/library/functions.html#range). 583 | _.range = function(start, stop, step) { 584 | if (arguments.length <= 1) { 585 | stop = start || 0; 586 | start = 0; 587 | } 588 | step = arguments[2] || 1; 589 | 590 | var length = Math.max(Math.ceil((stop - start) / step), 0); 591 | var idx = 0; 592 | var range = new Array(length); 593 | 594 | while(idx < length) { 595 | range[idx++] = start; 596 | start += step; 597 | } 598 | 599 | return range; 600 | }; 601 | 602 | // Function (ahem) Functions 603 | // ------------------ 604 | 605 | // Reusable constructor function for prototype setting. 606 | var ctor = function(){}; 607 | 608 | // Create a function bound to a given object (assigning `this`, and arguments, 609 | // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if 610 | // available. 611 | _.bind = function(func, context) { 612 | var args, bound; 613 | if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); 614 | if (!_.isFunction(func)) throw new TypeError; 615 | args = slice.call(arguments, 2); 616 | return bound = function() { 617 | if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); 618 | ctor.prototype = func.prototype; 619 | var self = new ctor; 620 | ctor.prototype = null; 621 | var result = func.apply(self, args.concat(slice.call(arguments))); 622 | if (Object(result) === result) return result; 623 | return self; 624 | }; 625 | }; 626 | 627 | // Partially apply a function by creating a version that has had some of its 628 | // arguments pre-filled, without changing its dynamic `this` context. _ acts 629 | // as a placeholder, allowing any combination of arguments to be pre-filled. 630 | _.partial = function(func) { 631 | var boundArgs = slice.call(arguments, 1); 632 | return function() { 633 | var position = 0; 634 | var args = boundArgs.slice(); 635 | for (var i = 0, length = args.length; i < length; i++) { 636 | if (args[i] === _) args[i] = arguments[position++]; 637 | } 638 | while (position < arguments.length) args.push(arguments[position++]); 639 | return func.apply(this, args); 640 | }; 641 | }; 642 | 643 | // Bind a number of an object's methods to that object. Remaining arguments 644 | // are the method names to be bound. Useful for ensuring that all callbacks 645 | // defined on an object belong to it. 646 | _.bindAll = function(obj) { 647 | var funcs = slice.call(arguments, 1); 648 | if (funcs.length === 0) throw new Error('bindAll must be passed function names'); 649 | each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); 650 | return obj; 651 | }; 652 | 653 | // Memoize an expensive function by storing its results. 654 | _.memoize = function(func, hasher) { 655 | var memo = {}; 656 | hasher || (hasher = _.identity); 657 | return function() { 658 | var key = hasher.apply(this, arguments); 659 | return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); 660 | }; 661 | }; 662 | 663 | // Delays a function for the given number of milliseconds, and then calls 664 | // it with the arguments supplied. 665 | _.delay = function(func, wait) { 666 | var args = slice.call(arguments, 2); 667 | return setTimeout(function(){ return func.apply(null, args); }, wait); 668 | }; 669 | 670 | // Defers a function, scheduling it to run after the current call stack has 671 | // cleared. 672 | _.defer = function(func) { 673 | return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); 674 | }; 675 | 676 | // Returns a function, that, when invoked, will only be triggered at most once 677 | // during a given window of time. Normally, the throttled function will run 678 | // as much as it can, without ever going more than once per `wait` duration; 679 | // but if you'd like to disable the execution on the leading edge, pass 680 | // `{leading: false}`. To disable execution on the trailing edge, ditto. 681 | _.throttle = function(func, wait, options) { 682 | var context, args, result; 683 | var timeout = null; 684 | var previous = 0; 685 | options || (options = {}); 686 | var later = function() { 687 | previous = options.leading === false ? 0 : _.now(); 688 | timeout = null; 689 | result = func.apply(context, args); 690 | context = args = null; 691 | }; 692 | return function() { 693 | var now = _.now(); 694 | if (!previous && options.leading === false) previous = now; 695 | var remaining = wait - (now - previous); 696 | context = this; 697 | args = arguments; 698 | if (remaining <= 0) { 699 | clearTimeout(timeout); 700 | timeout = null; 701 | previous = now; 702 | result = func.apply(context, args); 703 | context = args = null; 704 | } else if (!timeout && options.trailing !== false) { 705 | timeout = setTimeout(later, remaining); 706 | } 707 | return result; 708 | }; 709 | }; 710 | 711 | // Returns a function, that, as long as it continues to be invoked, will not 712 | // be triggered. The function will be called after it stops being called for 713 | // N milliseconds. If `immediate` is passed, trigger the function on the 714 | // leading edge, instead of the trailing. 715 | _.debounce = function(func, wait, immediate) { 716 | var timeout, args, context, timestamp, result; 717 | 718 | var later = function() { 719 | var last = _.now() - timestamp; 720 | if (last < wait) { 721 | timeout = setTimeout(later, wait - last); 722 | } else { 723 | timeout = null; 724 | if (!immediate) { 725 | result = func.apply(context, args); 726 | context = args = null; 727 | } 728 | } 729 | }; 730 | 731 | return function() { 732 | context = this; 733 | args = arguments; 734 | timestamp = _.now(); 735 | var callNow = immediate && !timeout; 736 | if (!timeout) { 737 | timeout = setTimeout(later, wait); 738 | } 739 | if (callNow) { 740 | result = func.apply(context, args); 741 | context = args = null; 742 | } 743 | 744 | return result; 745 | }; 746 | }; 747 | 748 | // Returns a function that will be executed at most one time, no matter how 749 | // often you call it. Useful for lazy initialization. 750 | _.once = function(func) { 751 | var ran = false, memo; 752 | return function() { 753 | if (ran) return memo; 754 | ran = true; 755 | memo = func.apply(this, arguments); 756 | func = null; 757 | return memo; 758 | }; 759 | }; 760 | 761 | // Returns the first function passed as an argument to the second, 762 | // allowing you to adjust arguments, run code before and after, and 763 | // conditionally execute the original function. 764 | _.wrap = function(func, wrapper) { 765 | return _.partial(wrapper, func); 766 | }; 767 | 768 | // Returns a function that is the composition of a list of functions, each 769 | // consuming the return value of the function that follows. 770 | _.compose = function() { 771 | var funcs = arguments; 772 | return function() { 773 | var args = arguments; 774 | for (var i = funcs.length - 1; i >= 0; i--) { 775 | args = [funcs[i].apply(this, args)]; 776 | } 777 | return args[0]; 778 | }; 779 | }; 780 | 781 | // Returns a function that will only be executed after being called N times. 782 | _.after = function(times, func) { 783 | return function() { 784 | if (--times < 1) { 785 | return func.apply(this, arguments); 786 | } 787 | }; 788 | }; 789 | 790 | // Object Functions 791 | // ---------------- 792 | 793 | // Retrieve the names of an object's properties. 794 | // Delegates to **ECMAScript 5**'s native `Object.keys` 795 | _.keys = function(obj) { 796 | if (!_.isObject(obj)) return []; 797 | if (nativeKeys) return nativeKeys(obj); 798 | var keys = []; 799 | for (var key in obj) if (_.has(obj, key)) keys.push(key); 800 | return keys; 801 | }; 802 | 803 | // Retrieve the values of an object's properties. 804 | _.values = function(obj) { 805 | var keys = _.keys(obj); 806 | var length = keys.length; 807 | var values = new Array(length); 808 | for (var i = 0; i < length; i++) { 809 | values[i] = obj[keys[i]]; 810 | } 811 | return values; 812 | }; 813 | 814 | // Convert an object into a list of `[key, value]` pairs. 815 | _.pairs = function(obj) { 816 | var keys = _.keys(obj); 817 | var length = keys.length; 818 | var pairs = new Array(length); 819 | for (var i = 0; i < length; i++) { 820 | pairs[i] = [keys[i], obj[keys[i]]]; 821 | } 822 | return pairs; 823 | }; 824 | 825 | // Invert the keys and values of an object. The values must be serializable. 826 | _.invert = function(obj) { 827 | var result = {}; 828 | var keys = _.keys(obj); 829 | for (var i = 0, length = keys.length; i < length; i++) { 830 | result[obj[keys[i]]] = keys[i]; 831 | } 832 | return result; 833 | }; 834 | 835 | // Return a sorted list of the function names available on the object. 836 | // Aliased as `methods` 837 | _.functions = _.methods = function(obj) { 838 | var names = []; 839 | for (var key in obj) { 840 | if (_.isFunction(obj[key])) names.push(key); 841 | } 842 | return names.sort(); 843 | }; 844 | 845 | // Extend a given object with all the properties in passed-in object(s). 846 | _.extend = function(obj) { 847 | each(slice.call(arguments, 1), function(source) { 848 | if (source) { 849 | for (var prop in source) { 850 | obj[prop] = source[prop]; 851 | } 852 | } 853 | }); 854 | return obj; 855 | }; 856 | 857 | // Return a copy of the object only containing the whitelisted properties. 858 | _.pick = function(obj) { 859 | var copy = {}; 860 | var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); 861 | each(keys, function(key) { 862 | if (key in obj) copy[key] = obj[key]; 863 | }); 864 | return copy; 865 | }; 866 | 867 | // Return a copy of the object without the blacklisted properties. 868 | _.omit = function(obj) { 869 | var copy = {}; 870 | var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); 871 | for (var key in obj) { 872 | if (!_.contains(keys, key)) copy[key] = obj[key]; 873 | } 874 | return copy; 875 | }; 876 | 877 | // Fill in a given object with default properties. 878 | _.defaults = function(obj) { 879 | each(slice.call(arguments, 1), function(source) { 880 | if (source) { 881 | for (var prop in source) { 882 | if (obj[prop] === void 0) obj[prop] = source[prop]; 883 | } 884 | } 885 | }); 886 | return obj; 887 | }; 888 | 889 | // Create a (shallow-cloned) duplicate of an object. 890 | _.clone = function(obj) { 891 | if (!_.isObject(obj)) return obj; 892 | return _.isArray(obj) ? obj.slice() : _.extend({}, obj); 893 | }; 894 | 895 | // Invokes interceptor with the obj, and then returns obj. 896 | // The primary purpose of this method is to "tap into" a method chain, in 897 | // order to perform operations on intermediate results within the chain. 898 | _.tap = function(obj, interceptor) { 899 | interceptor(obj); 900 | return obj; 901 | }; 902 | 903 | // Internal recursive comparison function for `isEqual`. 904 | var eq = function(a, b, aStack, bStack) { 905 | // Identical objects are equal. `0 === -0`, but they aren't identical. 906 | // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). 907 | if (a === b) return a !== 0 || 1 / a == 1 / b; 908 | // A strict comparison is necessary because `null == undefined`. 909 | if (a == null || b == null) return a === b; 910 | // Unwrap any wrapped objects. 911 | if (a instanceof _) a = a._wrapped; 912 | if (b instanceof _) b = b._wrapped; 913 | // Compare `[[Class]]` names. 914 | var className = toString.call(a); 915 | if (className != toString.call(b)) return false; 916 | switch (className) { 917 | // Strings, numbers, dates, and booleans are compared by value. 918 | case '[object String]': 919 | // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is 920 | // equivalent to `new String("5")`. 921 | return a == String(b); 922 | case '[object Number]': 923 | // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for 924 | // other numeric values. 925 | return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); 926 | case '[object Date]': 927 | case '[object Boolean]': 928 | // Coerce dates and booleans to numeric primitive values. Dates are compared by their 929 | // millisecond representations. Note that invalid dates with millisecond representations 930 | // of `NaN` are not equivalent. 931 | return +a == +b; 932 | // RegExps are compared by their source patterns and flags. 933 | case '[object RegExp]': 934 | return a.source == b.source && 935 | a.global == b.global && 936 | a.multiline == b.multiline && 937 | a.ignoreCase == b.ignoreCase; 938 | } 939 | if (typeof a != 'object' || typeof b != 'object') return false; 940 | // Assume equality for cyclic structures. The algorithm for detecting cyclic 941 | // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. 942 | var length = aStack.length; 943 | while (length--) { 944 | // Linear search. Performance is inversely proportional to the number of 945 | // unique nested structures. 946 | if (aStack[length] == a) return bStack[length] == b; 947 | } 948 | // Objects with different constructors are not equivalent, but `Object`s 949 | // from different frames are. 950 | var aCtor = a.constructor, bCtor = b.constructor; 951 | if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && 952 | _.isFunction(bCtor) && (bCtor instanceof bCtor)) 953 | && ('constructor' in a && 'constructor' in b)) { 954 | return false; 955 | } 956 | // Add the first object to the stack of traversed objects. 957 | aStack.push(a); 958 | bStack.push(b); 959 | var size = 0, result = true; 960 | // Recursively compare objects and arrays. 961 | if (className == '[object Array]') { 962 | // Compare array lengths to determine if a deep comparison is necessary. 963 | size = a.length; 964 | result = size == b.length; 965 | if (result) { 966 | // Deep compare the contents, ignoring non-numeric properties. 967 | while (size--) { 968 | if (!(result = eq(a[size], b[size], aStack, bStack))) break; 969 | } 970 | } 971 | } else { 972 | // Deep compare objects. 973 | for (var key in a) { 974 | if (_.has(a, key)) { 975 | // Count the expected number of properties. 976 | size++; 977 | // Deep compare each member. 978 | if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; 979 | } 980 | } 981 | // Ensure that both objects contain the same number of properties. 982 | if (result) { 983 | for (key in b) { 984 | if (_.has(b, key) && !(size--)) break; 985 | } 986 | result = !size; 987 | } 988 | } 989 | // Remove the first object from the stack of traversed objects. 990 | aStack.pop(); 991 | bStack.pop(); 992 | return result; 993 | }; 994 | 995 | // Perform a deep comparison to check if two objects are equal. 996 | _.isEqual = function(a, b) { 997 | return eq(a, b, [], []); 998 | }; 999 | 1000 | // Is a given array, string, or object empty? 1001 | // An "empty" object has no enumerable own-properties. 1002 | _.isEmpty = function(obj) { 1003 | if (obj == null) return true; 1004 | if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; 1005 | for (var key in obj) if (_.has(obj, key)) return false; 1006 | return true; 1007 | }; 1008 | 1009 | // Is a given value a DOM element? 1010 | _.isElement = function(obj) { 1011 | return !!(obj && obj.nodeType === 1); 1012 | }; 1013 | 1014 | // Is a given value an array? 1015 | // Delegates to ECMA5's native Array.isArray 1016 | _.isArray = nativeIsArray || function(obj) { 1017 | return toString.call(obj) == '[object Array]'; 1018 | }; 1019 | 1020 | // Is a given variable an object? 1021 | _.isObject = function(obj) { 1022 | return obj === Object(obj); 1023 | }; 1024 | 1025 | // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. 1026 | each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { 1027 | _['is' + name] = function(obj) { 1028 | return toString.call(obj) == '[object ' + name + ']'; 1029 | }; 1030 | }); 1031 | 1032 | // Define a fallback version of the method in browsers (ahem, IE), where 1033 | // there isn't any inspectable "Arguments" type. 1034 | if (!_.isArguments(arguments)) { 1035 | _.isArguments = function(obj) { 1036 | return !!(obj && _.has(obj, 'callee')); 1037 | }; 1038 | } 1039 | 1040 | // Optimize `isFunction` if appropriate. 1041 | if (typeof (/./) !== 'function') { 1042 | _.isFunction = function(obj) { 1043 | return typeof obj === 'function'; 1044 | }; 1045 | } 1046 | 1047 | // Is a given object a finite number? 1048 | _.isFinite = function(obj) { 1049 | return isFinite(obj) && !isNaN(parseFloat(obj)); 1050 | }; 1051 | 1052 | // Is the given value `NaN`? (NaN is the only number which does not equal itself). 1053 | _.isNaN = function(obj) { 1054 | return _.isNumber(obj) && obj != +obj; 1055 | }; 1056 | 1057 | // Is a given value a boolean? 1058 | _.isBoolean = function(obj) { 1059 | return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; 1060 | }; 1061 | 1062 | // Is a given value equal to null? 1063 | _.isNull = function(obj) { 1064 | return obj === null; 1065 | }; 1066 | 1067 | // Is a given variable undefined? 1068 | _.isUndefined = function(obj) { 1069 | return obj === void 0; 1070 | }; 1071 | 1072 | // Shortcut function for checking if an object has a given property directly 1073 | // on itself (in other words, not on a prototype). 1074 | _.has = function(obj, key) { 1075 | return hasOwnProperty.call(obj, key); 1076 | }; 1077 | 1078 | // Utility Functions 1079 | // ----------------- 1080 | 1081 | // Run Underscore.js in *noConflict* mode, returning the `_` variable to its 1082 | // previous owner. Returns a reference to the Underscore object. 1083 | _.noConflict = function() { 1084 | root._ = previousUnderscore; 1085 | return this; 1086 | }; 1087 | 1088 | // Keep the identity function around for default iterators. 1089 | _.identity = function(value) { 1090 | return value; 1091 | }; 1092 | 1093 | _.constant = function(value) { 1094 | return function () { 1095 | return value; 1096 | }; 1097 | }; 1098 | 1099 | _.property = function(key) { 1100 | return function(obj) { 1101 | return obj[key]; 1102 | }; 1103 | }; 1104 | 1105 | // Returns a predicate for checking whether an object has a given set of `key:value` pairs. 1106 | _.matches = function(attrs) { 1107 | return function(obj) { 1108 | if (obj === attrs) return true; //avoid comparing an object to itself. 1109 | for (var key in attrs) { 1110 | if (attrs[key] !== obj[key]) 1111 | return false; 1112 | } 1113 | return true; 1114 | } 1115 | }; 1116 | 1117 | // Run a function **n** times. 1118 | _.times = function(n, iterator, context) { 1119 | var accum = Array(Math.max(0, n)); 1120 | for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i); 1121 | return accum; 1122 | }; 1123 | 1124 | // Return a random integer between min and max (inclusive). 1125 | _.random = function(min, max) { 1126 | if (max == null) { 1127 | max = min; 1128 | min = 0; 1129 | } 1130 | return min + Math.floor(Math.random() * (max - min + 1)); 1131 | }; 1132 | 1133 | // A (possibly faster) way to get the current timestamp as an integer. 1134 | _.now = Date.now || function() { return new Date().getTime(); }; 1135 | 1136 | // List of HTML entities for escaping. 1137 | var entityMap = { 1138 | escape: { 1139 | '&': '&', 1140 | '<': '<', 1141 | '>': '>', 1142 | '"': '"', 1143 | "'": ''' 1144 | } 1145 | }; 1146 | entityMap.unescape = _.invert(entityMap.escape); 1147 | 1148 | // Regexes containing the keys and values listed immediately above. 1149 | var entityRegexes = { 1150 | escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'), 1151 | unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g') 1152 | }; 1153 | 1154 | // Functions for escaping and unescaping strings to/from HTML interpolation. 1155 | _.each(['escape', 'unescape'], function(method) { 1156 | _[method] = function(string) { 1157 | if (string == null) return ''; 1158 | return ('' + string).replace(entityRegexes[method], function(match) { 1159 | return entityMap[method][match]; 1160 | }); 1161 | }; 1162 | }); 1163 | 1164 | // If the value of the named `property` is a function then invoke it with the 1165 | // `object` as context; otherwise, return it. 1166 | _.result = function(object, property) { 1167 | if (object == null) return void 0; 1168 | var value = object[property]; 1169 | return _.isFunction(value) ? value.call(object) : value; 1170 | }; 1171 | 1172 | // Add your own custom functions to the Underscore object. 1173 | _.mixin = function(obj) { 1174 | each(_.functions(obj), function(name) { 1175 | var func = _[name] = obj[name]; 1176 | _.prototype[name] = function() { 1177 | var args = [this._wrapped]; 1178 | push.apply(args, arguments); 1179 | return result.call(this, func.apply(_, args)); 1180 | }; 1181 | }); 1182 | }; 1183 | 1184 | // Generate a unique integer id (unique within the entire client session). 1185 | // Useful for temporary DOM ids. 1186 | var idCounter = 0; 1187 | _.uniqueId = function(prefix) { 1188 | var id = ++idCounter + ''; 1189 | return prefix ? prefix + id : id; 1190 | }; 1191 | 1192 | // By default, Underscore uses ERB-style template delimiters, change the 1193 | // following template settings to use alternative delimiters. 1194 | _.templateSettings = { 1195 | evaluate : /<%([\s\S]+?)%>/g, 1196 | interpolate : /<%=([\s\S]+?)%>/g, 1197 | escape : /<%-([\s\S]+?)%>/g 1198 | }; 1199 | 1200 | // When customizing `templateSettings`, if you don't want to define an 1201 | // interpolation, evaluation or escaping regex, we need one that is 1202 | // guaranteed not to match. 1203 | var noMatch = /(.)^/; 1204 | 1205 | // Certain characters need to be escaped so that they can be put into a 1206 | // string literal. 1207 | var escapes = { 1208 | "'": "'", 1209 | '\\': '\\', 1210 | '\r': 'r', 1211 | '\n': 'n', 1212 | '\t': 't', 1213 | '\u2028': 'u2028', 1214 | '\u2029': 'u2029' 1215 | }; 1216 | 1217 | var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; 1218 | 1219 | // JavaScript micro-templating, similar to John Resig's implementation. 1220 | // Underscore templating handles arbitrary delimiters, preserves whitespace, 1221 | // and correctly escapes quotes within interpolated code. 1222 | _.template = function(text, data, settings) { 1223 | var render; 1224 | settings = _.defaults({}, settings, _.templateSettings); 1225 | 1226 | // Combine delimiters into one regular expression via alternation. 1227 | var matcher = new RegExp([ 1228 | (settings.escape || noMatch).source, 1229 | (settings.interpolate || noMatch).source, 1230 | (settings.evaluate || noMatch).source 1231 | ].join('|') + '|$', 'g'); 1232 | 1233 | // Compile the template source, escaping string literals appropriately. 1234 | var index = 0; 1235 | var source = "__p+='"; 1236 | text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { 1237 | source += text.slice(index, offset) 1238 | .replace(escaper, function(match) { return '\\' + escapes[match]; }); 1239 | 1240 | if (escape) { 1241 | source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; 1242 | } 1243 | if (interpolate) { 1244 | source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; 1245 | } 1246 | if (evaluate) { 1247 | source += "';\n" + evaluate + "\n__p+='"; 1248 | } 1249 | index = offset + match.length; 1250 | return match; 1251 | }); 1252 | source += "';\n"; 1253 | 1254 | // If a variable is not specified, place data values in local scope. 1255 | if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; 1256 | 1257 | source = "var __t,__p='',__j=Array.prototype.join," + 1258 | "print=function(){__p+=__j.call(arguments,'');};\n" + 1259 | source + "return __p;\n"; 1260 | 1261 | try { 1262 | render = new Function(settings.variable || 'obj', '_', source); 1263 | } catch (e) { 1264 | e.source = source; 1265 | throw e; 1266 | } 1267 | 1268 | if (data) return render(data, _); 1269 | var template = function(data) { 1270 | return render.call(this, data, _); 1271 | }; 1272 | 1273 | // Provide the compiled function source as a convenience for precompilation. 1274 | template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; 1275 | 1276 | return template; 1277 | }; 1278 | 1279 | // Add a "chain" function, which will delegate to the wrapper. 1280 | _.chain = function(obj) { 1281 | return _(obj).chain(); 1282 | }; 1283 | 1284 | // OOP 1285 | // --------------- 1286 | // If Underscore is called as a function, it returns a wrapped object that 1287 | // can be used OO-style. This wrapper holds altered versions of all the 1288 | // underscore functions. Wrapped objects may be chained. 1289 | 1290 | // Helper function to continue chaining intermediate results. 1291 | var result = function(obj) { 1292 | return this._chain ? _(obj).chain() : obj; 1293 | }; 1294 | 1295 | // Add all of the Underscore functions to the wrapper object. 1296 | _.mixin(_); 1297 | 1298 | // Add all mutator Array functions to the wrapper. 1299 | each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { 1300 | var method = ArrayProto[name]; 1301 | _.prototype[name] = function() { 1302 | var obj = this._wrapped; 1303 | method.apply(obj, arguments); 1304 | if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0]; 1305 | return result.call(this, obj); 1306 | }; 1307 | }); 1308 | 1309 | // Add all accessor Array functions to the wrapper. 1310 | each(['concat', 'join', 'slice'], function(name) { 1311 | var method = ArrayProto[name]; 1312 | _.prototype[name] = function() { 1313 | return result.call(this, method.apply(this._wrapped, arguments)); 1314 | }; 1315 | }); 1316 | 1317 | _.extend(_.prototype, { 1318 | 1319 | // Start chaining a wrapped Underscore object. 1320 | chain: function() { 1321 | this._chain = true; 1322 | return this; 1323 | }, 1324 | 1325 | // Extracts the result from a wrapped and chained object. 1326 | value: function() { 1327 | return this._wrapped; 1328 | } 1329 | 1330 | }); 1331 | 1332 | // AMD registration happens at the end for compatibility with AMD loaders 1333 | // that may not enforce next-turn semantics on modules. Even though general 1334 | // practice for AMD registration is to be anonymous, underscore registers 1335 | // as a named module because, like jQuery, it is a base library that is 1336 | // popular enough to be bundled in a third party lib, but not be part of 1337 | // an AMD load request. Those cases could generate an error when an 1338 | // anonymous define() is called outside of a loader request. 1339 | if (typeof define === 'function' && define.amd) { 1340 | define('underscore', [], function() { 1341 | return _; 1342 | }); 1343 | } 1344 | }).call(this); 1345 | -------------------------------------------------------------------------------- /js/backbone.js: -------------------------------------------------------------------------------- 1 | // Backbone.js 1.1.2 2 | 3 | // (c) 2010-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors 4 | // Backbone may be freely distributed under the MIT license. 5 | // For all details and documentation: 6 | // http://backbonejs.org 7 | 8 | (function(root, factory) { 9 | 10 | // Set up Backbone appropriately for the environment. Start with AMD. 11 | if (typeof define === 'function' && define.amd) { 12 | define(['underscore', 'jquery', 'exports'], function(_, $, exports) { 13 | // Export global even in AMD case in case this script is loaded with 14 | // others that may still expect a global Backbone. 15 | root.Backbone = factory(root, exports, _, $); 16 | }); 17 | 18 | // Next for Node.js or CommonJS. jQuery may not be needed as a module. 19 | } else if (typeof exports !== 'undefined') { 20 | var _ = require('underscore'); 21 | factory(root, exports, _); 22 | 23 | // Finally, as a browser global. 24 | } else { 25 | root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$)); 26 | } 27 | 28 | }(this, function(root, Backbone, _, $) { 29 | 30 | // Initial Setup 31 | // ------------- 32 | 33 | // Save the previous value of the `Backbone` variable, so that it can be 34 | // restored later on, if `noConflict` is used. 35 | var previousBackbone = root.Backbone; 36 | 37 | // Create local references to array methods we'll want to use later. 38 | var array = []; 39 | var push = array.push; 40 | var slice = array.slice; 41 | var splice = array.splice; 42 | 43 | // Current version of the library. Keep in sync with `package.json`. 44 | Backbone.VERSION = '1.1.2'; 45 | 46 | // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns 47 | // the `$` variable. 48 | Backbone.$ = $; 49 | 50 | // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable 51 | // to its previous owner. Returns a reference to this Backbone object. 52 | Backbone.noConflict = function() { 53 | root.Backbone = previousBackbone; 54 | return this; 55 | }; 56 | 57 | // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option 58 | // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and 59 | // set a `X-Http-Method-Override` header. 60 | Backbone.emulateHTTP = false; 61 | 62 | // Turn on `emulateJSON` to support legacy servers that can't deal with direct 63 | // `application/json` requests ... will encode the body as 64 | // `application/x-www-form-urlencoded` instead and will send the model in a 65 | // form param named `model`. 66 | Backbone.emulateJSON = false; 67 | 68 | // Backbone.Events 69 | // --------------- 70 | 71 | // A module that can be mixed in to *any object* in order to provide it with 72 | // custom events. You may bind with `on` or remove with `off` callback 73 | // functions to an event; `trigger`-ing an event fires all callbacks in 74 | // succession. 75 | // 76 | // var object = {}; 77 | // _.extend(object, Backbone.Events); 78 | // object.on('expand', function(){ alert('expanded'); }); 79 | // object.trigger('expand'); 80 | // 81 | var Events = Backbone.Events = { 82 | 83 | // Bind an event to a `callback` function. Passing `"all"` will bind 84 | // the callback to all events fired. 85 | on: function(name, callback, context) { 86 | if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; 87 | this._events || (this._events = {}); 88 | var events = this._events[name] || (this._events[name] = []); 89 | events.push({callback: callback, context: context, ctx: context || this}); 90 | return this; 91 | }, 92 | 93 | // Bind an event to only be triggered a single time. After the first time 94 | // the callback is invoked, it will be removed. 95 | once: function(name, callback, context) { 96 | if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; 97 | var self = this; 98 | var once = _.once(function() { 99 | self.off(name, once); 100 | callback.apply(this, arguments); 101 | }); 102 | once._callback = callback; 103 | return this.on(name, once, context); 104 | }, 105 | 106 | // Remove one or many callbacks. If `context` is null, removes all 107 | // callbacks with that function. If `callback` is null, removes all 108 | // callbacks for the event. If `name` is null, removes all bound 109 | // callbacks for all events. 110 | off: function(name, callback, context) { 111 | var retain, ev, events, names, i, l, j, k; 112 | if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; 113 | if (!name && !callback && !context) { 114 | this._events = void 0; 115 | return this; 116 | } 117 | names = name ? [name] : _.keys(this._events); 118 | for (i = 0, l = names.length; i < l; i++) { 119 | name = names[i]; 120 | if (events = this._events[name]) { 121 | this._events[name] = retain = []; 122 | if (callback || context) { 123 | for (j = 0, k = events.length; j < k; j++) { 124 | ev = events[j]; 125 | if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || 126 | (context && context !== ev.context)) { 127 | retain.push(ev); 128 | } 129 | } 130 | } 131 | if (!retain.length) delete this._events[name]; 132 | } 133 | } 134 | 135 | return this; 136 | }, 137 | 138 | // Trigger one or many events, firing all bound callbacks. Callbacks are 139 | // passed the same arguments as `trigger` is, apart from the event name 140 | // (unless you're listening on `"all"`, which will cause your callback to 141 | // receive the true name of the event as the first argument). 142 | trigger: function(name) { 143 | if (!this._events) return this; 144 | var args = slice.call(arguments, 1); 145 | if (!eventsApi(this, 'trigger', name, args)) return this; 146 | var events = this._events[name]; 147 | var allEvents = this._events.all; 148 | if (events) triggerEvents(events, args); 149 | if (allEvents) triggerEvents(allEvents, arguments); 150 | return this; 151 | }, 152 | 153 | // Tell this object to stop listening to either specific events ... or 154 | // to every object it's currently listening to. 155 | stopListening: function(obj, name, callback) { 156 | var listeningTo = this._listeningTo; 157 | if (!listeningTo) return this; 158 | var remove = !name && !callback; 159 | if (!callback && typeof name === 'object') callback = this; 160 | if (obj) (listeningTo = {})[obj._listenId] = obj; 161 | for (var id in listeningTo) { 162 | obj = listeningTo[id]; 163 | obj.off(name, callback, this); 164 | if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id]; 165 | } 166 | return this; 167 | } 168 | 169 | }; 170 | 171 | // Regular expression used to split event strings. 172 | var eventSplitter = /\s+/; 173 | 174 | // Implement fancy features of the Events API such as multiple event 175 | // names `"change blur"` and jQuery-style event maps `{change: action}` 176 | // in terms of the existing API. 177 | var eventsApi = function(obj, action, name, rest) { 178 | if (!name) return true; 179 | 180 | // Handle event maps. 181 | if (typeof name === 'object') { 182 | for (var key in name) { 183 | obj[action].apply(obj, [key, name[key]].concat(rest)); 184 | } 185 | return false; 186 | } 187 | 188 | // Handle space separated event names. 189 | if (eventSplitter.test(name)) { 190 | var names = name.split(eventSplitter); 191 | for (var i = 0, l = names.length; i < l; i++) { 192 | obj[action].apply(obj, [names[i]].concat(rest)); 193 | } 194 | return false; 195 | } 196 | 197 | return true; 198 | }; 199 | 200 | // A difficult-to-believe, but optimized internal dispatch function for 201 | // triggering events. Tries to keep the usual cases speedy (most internal 202 | // Backbone events have 3 arguments). 203 | var triggerEvents = function(events, args) { 204 | var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; 205 | switch (args.length) { 206 | case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; 207 | case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; 208 | case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; 209 | case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; 210 | default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return; 211 | } 212 | }; 213 | 214 | var listenMethods = {listenTo: 'on', listenToOnce: 'once'}; 215 | 216 | // Inversion-of-control versions of `on` and `once`. Tell *this* object to 217 | // listen to an event in another object ... keeping track of what it's 218 | // listening to. 219 | _.each(listenMethods, function(implementation, method) { 220 | Events[method] = function(obj, name, callback) { 221 | var listeningTo = this._listeningTo || (this._listeningTo = {}); 222 | var id = obj._listenId || (obj._listenId = _.uniqueId('l')); 223 | listeningTo[id] = obj; 224 | if (!callback && typeof name === 'object') callback = this; 225 | obj[implementation](name, callback, this); 226 | return this; 227 | }; 228 | }); 229 | 230 | // Aliases for backwards compatibility. 231 | Events.bind = Events.on; 232 | Events.unbind = Events.off; 233 | 234 | // Allow the `Backbone` object to serve as a global event bus, for folks who 235 | // want global "pubsub" in a convenient place. 236 | _.extend(Backbone, Events); 237 | 238 | // Backbone.Model 239 | // -------------- 240 | 241 | // Backbone **Models** are the basic data object in the framework -- 242 | // frequently representing a row in a table in a database on your server. 243 | // A discrete chunk of data and a bunch of useful, related methods for 244 | // performing computations and transformations on that data. 245 | 246 | // Create a new model with the specified attributes. A client id (`cid`) 247 | // is automatically generated and assigned for you. 248 | var Model = Backbone.Model = function(attributes, options) { 249 | var attrs = attributes || {}; 250 | options || (options = {}); 251 | this.cid = _.uniqueId('c'); 252 | this.attributes = {}; 253 | if (options.collection) this.collection = options.collection; 254 | if (options.parse) attrs = this.parse(attrs, options) || {}; 255 | attrs = _.defaults({}, attrs, _.result(this, 'defaults')); 256 | this.set(attrs, options); 257 | this.changed = {}; 258 | this.initialize.apply(this, arguments); 259 | }; 260 | 261 | // Attach all inheritable methods to the Model prototype. 262 | _.extend(Model.prototype, Events, { 263 | 264 | // A hash of attributes whose current and previous value differ. 265 | changed: null, 266 | 267 | // The value returned during the last failed validation. 268 | validationError: null, 269 | 270 | // The default name for the JSON `id` attribute is `"id"`. MongoDB and 271 | // CouchDB users may want to set this to `"_id"`. 272 | idAttribute: 'id', 273 | 274 | // Initialize is an empty function by default. Override it with your own 275 | // initialization logic. 276 | initialize: function(){}, 277 | 278 | // Return a copy of the model's `attributes` object. 279 | toJSON: function(options) { 280 | return _.clone(this.attributes); 281 | }, 282 | 283 | // Proxy `Backbone.sync` by default -- but override this if you need 284 | // custom syncing semantics for *this* particular model. 285 | sync: function() { 286 | return Backbone.sync.apply(this, arguments); 287 | }, 288 | 289 | // Get the value of an attribute. 290 | get: function(attr) { 291 | return this.attributes[attr]; 292 | }, 293 | 294 | // Get the HTML-escaped value of an attribute. 295 | escape: function(attr) { 296 | return _.escape(this.get(attr)); 297 | }, 298 | 299 | // Returns `true` if the attribute contains a value that is not null 300 | // or undefined. 301 | has: function(attr) { 302 | return this.get(attr) != null; 303 | }, 304 | 305 | // Set a hash of model attributes on the object, firing `"change"`. This is 306 | // the core primitive operation of a model, updating the data and notifying 307 | // anyone who needs to know about the change in state. The heart of the beast. 308 | set: function(key, val, options) { 309 | var attr, attrs, unset, changes, silent, changing, prev, current; 310 | if (key == null) return this; 311 | 312 | // Handle both `"key", value` and `{key: value}` -style arguments. 313 | if (typeof key === 'object') { 314 | attrs = key; 315 | options = val; 316 | } else { 317 | (attrs = {})[key] = val; 318 | } 319 | 320 | options || (options = {}); 321 | 322 | // Run validation. 323 | if (!this._validate(attrs, options)) return false; 324 | 325 | // Extract attributes and options. 326 | unset = options.unset; 327 | silent = options.silent; 328 | changes = []; 329 | changing = this._changing; 330 | this._changing = true; 331 | 332 | if (!changing) { 333 | this._previousAttributes = _.clone(this.attributes); 334 | this.changed = {}; 335 | } 336 | current = this.attributes, prev = this._previousAttributes; 337 | 338 | // Check for changes of `id`. 339 | if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; 340 | 341 | // For each `set` attribute, update or delete the current value. 342 | for (attr in attrs) { 343 | val = attrs[attr]; 344 | if (!_.isEqual(current[attr], val)) changes.push(attr); 345 | if (!_.isEqual(prev[attr], val)) { 346 | this.changed[attr] = val; 347 | } else { 348 | delete this.changed[attr]; 349 | } 350 | unset ? delete current[attr] : current[attr] = val; 351 | } 352 | 353 | // Trigger all relevant attribute changes. 354 | if (!silent) { 355 | if (changes.length) this._pending = options; 356 | for (var i = 0, l = changes.length; i < l; i++) { 357 | this.trigger('change:' + changes[i], this, current[changes[i]], options); 358 | } 359 | } 360 | 361 | // You might be wondering why there's a `while` loop here. Changes can 362 | // be recursively nested within `"change"` events. 363 | if (changing) return this; 364 | if (!silent) { 365 | while (this._pending) { 366 | options = this._pending; 367 | this._pending = false; 368 | this.trigger('change', this, options); 369 | } 370 | } 371 | this._pending = false; 372 | this._changing = false; 373 | return this; 374 | }, 375 | 376 | // Remove an attribute from the model, firing `"change"`. `unset` is a noop 377 | // if the attribute doesn't exist. 378 | unset: function(attr, options) { 379 | return this.set(attr, void 0, _.extend({}, options, {unset: true})); 380 | }, 381 | 382 | // Clear all attributes on the model, firing `"change"`. 383 | clear: function(options) { 384 | var attrs = {}; 385 | for (var key in this.attributes) attrs[key] = void 0; 386 | return this.set(attrs, _.extend({}, options, {unset: true})); 387 | }, 388 | 389 | // Determine if the model has changed since the last `"change"` event. 390 | // If you specify an attribute name, determine if that attribute has changed. 391 | hasChanged: function(attr) { 392 | if (attr == null) return !_.isEmpty(this.changed); 393 | return _.has(this.changed, attr); 394 | }, 395 | 396 | // Return an object containing all the attributes that have changed, or 397 | // false if there are no changed attributes. Useful for determining what 398 | // parts of a view need to be updated and/or what attributes need to be 399 | // persisted to the server. Unset attributes will be set to undefined. 400 | // You can also pass an attributes object to diff against the model, 401 | // determining if there *would be* a change. 402 | changedAttributes: function(diff) { 403 | if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; 404 | var val, changed = false; 405 | var old = this._changing ? this._previousAttributes : this.attributes; 406 | for (var attr in diff) { 407 | if (_.isEqual(old[attr], (val = diff[attr]))) continue; 408 | (changed || (changed = {}))[attr] = val; 409 | } 410 | return changed; 411 | }, 412 | 413 | // Get the previous value of an attribute, recorded at the time the last 414 | // `"change"` event was fired. 415 | previous: function(attr) { 416 | if (attr == null || !this._previousAttributes) return null; 417 | return this._previousAttributes[attr]; 418 | }, 419 | 420 | // Get all of the attributes of the model at the time of the previous 421 | // `"change"` event. 422 | previousAttributes: function() { 423 | return _.clone(this._previousAttributes); 424 | }, 425 | 426 | // Fetch the model from the server. If the server's representation of the 427 | // model differs from its current attributes, they will be overridden, 428 | // triggering a `"change"` event. 429 | fetch: function(options) { 430 | options = options ? _.clone(options) : {}; 431 | if (options.parse === void 0) options.parse = true; 432 | var model = this; 433 | var success = options.success; 434 | options.success = function(resp) { 435 | if (!model.set(model.parse(resp, options), options)) return false; 436 | if (success) success(model, resp, options); 437 | model.trigger('sync', model, resp, options); 438 | }; 439 | wrapError(this, options); 440 | return this.sync('read', this, options); 441 | }, 442 | 443 | // Set a hash of model attributes, and sync the model to the server. 444 | // If the server returns an attributes hash that differs, the model's 445 | // state will be `set` again. 446 | save: function(key, val, options) { 447 | var attrs, method, xhr, attributes = this.attributes; 448 | 449 | // Handle both `"key", value` and `{key: value}` -style arguments. 450 | if (key == null || typeof key === 'object') { 451 | attrs = key; 452 | options = val; 453 | } else { 454 | (attrs = {})[key] = val; 455 | } 456 | 457 | options = _.extend({validate: true}, options); 458 | 459 | // If we're not waiting and attributes exist, save acts as 460 | // `set(attr).save(null, opts)` with validation. Otherwise, check if 461 | // the model will be valid when the attributes, if any, are set. 462 | if (attrs && !options.wait) { 463 | if (!this.set(attrs, options)) return false; 464 | } else { 465 | if (!this._validate(attrs, options)) return false; 466 | } 467 | 468 | // Set temporary attributes if `{wait: true}`. 469 | if (attrs && options.wait) { 470 | this.attributes = _.extend({}, attributes, attrs); 471 | } 472 | 473 | // After a successful server-side save, the client is (optionally) 474 | // updated with the server-side state. 475 | if (options.parse === void 0) options.parse = true; 476 | var model = this; 477 | var success = options.success; 478 | options.success = function(resp) { 479 | // Ensure attributes are restored during synchronous saves. 480 | model.attributes = attributes; 481 | var serverAttrs = model.parse(resp, options); 482 | if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); 483 | if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) { 484 | return false; 485 | } 486 | if (success) success(model, resp, options); 487 | model.trigger('sync', model, resp, options); 488 | }; 489 | wrapError(this, options); 490 | 491 | method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); 492 | if (method === 'patch') options.attrs = attrs; 493 | xhr = this.sync(method, this, options); 494 | 495 | // Restore attributes. 496 | if (attrs && options.wait) this.attributes = attributes; 497 | 498 | return xhr; 499 | }, 500 | 501 | // Destroy this model on the server if it was already persisted. 502 | // Optimistically removes the model from its collection, if it has one. 503 | // If `wait: true` is passed, waits for the server to respond before removal. 504 | destroy: function(options) { 505 | options = options ? _.clone(options) : {}; 506 | var model = this; 507 | var success = options.success; 508 | 509 | var destroy = function() { 510 | model.trigger('destroy', model, model.collection, options); 511 | }; 512 | 513 | options.success = function(resp) { 514 | if (options.wait || model.isNew()) destroy(); 515 | if (success) success(model, resp, options); 516 | if (!model.isNew()) model.trigger('sync', model, resp, options); 517 | }; 518 | 519 | if (this.isNew()) { 520 | options.success(); 521 | return false; 522 | } 523 | wrapError(this, options); 524 | 525 | var xhr = this.sync('delete', this, options); 526 | if (!options.wait) destroy(); 527 | return xhr; 528 | }, 529 | 530 | // Default URL for the model's representation on the server -- if you're 531 | // using Backbone's restful methods, override this to change the endpoint 532 | // that will be called. 533 | url: function() { 534 | var base = 535 | _.result(this, 'urlRoot') || 536 | _.result(this.collection, 'url') || 537 | urlError(); 538 | if (this.isNew()) return base; 539 | return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id); 540 | }, 541 | 542 | // **parse** converts a response into the hash of attributes to be `set` on 543 | // the model. The default implementation is just to pass the response along. 544 | parse: function(resp, options) { 545 | return resp; 546 | }, 547 | 548 | // Create a new model with identical attributes to this one. 549 | clone: function() { 550 | return new this.constructor(this.attributes); 551 | }, 552 | 553 | // A model is new if it has never been saved to the server, and lacks an id. 554 | isNew: function() { 555 | return !this.has(this.idAttribute); 556 | }, 557 | 558 | // Check if the model is currently in a valid state. 559 | isValid: function(options) { 560 | return this._validate({}, _.extend(options || {}, { validate: true })); 561 | }, 562 | 563 | // Run validation against the next complete set of model attributes, 564 | // returning `true` if all is well. Otherwise, fire an `"invalid"` event. 565 | _validate: function(attrs, options) { 566 | if (!options.validate || !this.validate) return true; 567 | attrs = _.extend({}, this.attributes, attrs); 568 | var error = this.validationError = this.validate(attrs, options) || null; 569 | if (!error) return true; 570 | this.trigger('invalid', this, error, _.extend(options, {validationError: error})); 571 | return false; 572 | } 573 | 574 | }); 575 | 576 | // Underscore methods that we want to implement on the Model. 577 | var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit']; 578 | 579 | // Mix in each Underscore method as a proxy to `Model#attributes`. 580 | _.each(modelMethods, function(method) { 581 | Model.prototype[method] = function() { 582 | var args = slice.call(arguments); 583 | args.unshift(this.attributes); 584 | return _[method].apply(_, args); 585 | }; 586 | }); 587 | 588 | // Backbone.Collection 589 | // ------------------- 590 | 591 | // If models tend to represent a single row of data, a Backbone Collection is 592 | // more analagous to a table full of data ... or a small slice or page of that 593 | // table, or a collection of rows that belong together for a particular reason 594 | // -- all of the messages in this particular folder, all of the documents 595 | // belonging to this particular author, and so on. Collections maintain 596 | // indexes of their models, both in order, and for lookup by `id`. 597 | 598 | // Create a new **Collection**, perhaps to contain a specific type of `model`. 599 | // If a `comparator` is specified, the Collection will maintain 600 | // its models in sort order, as they're added and removed. 601 | var Collection = Backbone.Collection = function(models, options) { 602 | options || (options = {}); 603 | if (options.model) this.model = options.model; 604 | if (options.comparator !== void 0) this.comparator = options.comparator; 605 | this._reset(); 606 | this.initialize.apply(this, arguments); 607 | if (models) this.reset(models, _.extend({silent: true}, options)); 608 | }; 609 | 610 | // Default options for `Collection#set`. 611 | var setOptions = {add: true, remove: true, merge: true}; 612 | var addOptions = {add: true, remove: false}; 613 | 614 | // Define the Collection's inheritable methods. 615 | _.extend(Collection.prototype, Events, { 616 | 617 | // The default model for a collection is just a **Backbone.Model**. 618 | // This should be overridden in most cases. 619 | model: Model, 620 | 621 | // Initialize is an empty function by default. Override it with your own 622 | // initialization logic. 623 | initialize: function(){}, 624 | 625 | // The JSON representation of a Collection is an array of the 626 | // models' attributes. 627 | toJSON: function(options) { 628 | return this.map(function(model){ return model.toJSON(options); }); 629 | }, 630 | 631 | // Proxy `Backbone.sync` by default. 632 | sync: function() { 633 | return Backbone.sync.apply(this, arguments); 634 | }, 635 | 636 | // Add a model, or list of models to the set. 637 | add: function(models, options) { 638 | return this.set(models, _.extend({merge: false}, options, addOptions)); 639 | }, 640 | 641 | // Remove a model, or a list of models from the set. 642 | remove: function(models, options) { 643 | var singular = !_.isArray(models); 644 | models = singular ? [models] : _.clone(models); 645 | options || (options = {}); 646 | var i, l, index, model; 647 | for (i = 0, l = models.length; i < l; i++) { 648 | model = models[i] = this.get(models[i]); 649 | if (!model) continue; 650 | delete this._byId[model.id]; 651 | delete this._byId[model.cid]; 652 | index = this.indexOf(model); 653 | this.models.splice(index, 1); 654 | this.length--; 655 | if (!options.silent) { 656 | options.index = index; 657 | model.trigger('remove', model, this, options); 658 | } 659 | this._removeReference(model, options); 660 | } 661 | return singular ? models[0] : models; 662 | }, 663 | 664 | // Update a collection by `set`-ing a new list of models, adding new ones, 665 | // removing models that are no longer present, and merging models that 666 | // already exist in the collection, as necessary. Similar to **Model#set**, 667 | // the core operation for updating the data contained by the collection. 668 | set: function(models, options) { 669 | options = _.defaults({}, options, setOptions); 670 | if (options.parse) models = this.parse(models, options); 671 | var singular = !_.isArray(models); 672 | models = singular ? (models ? [models] : []) : _.clone(models); 673 | var i, l, id, model, attrs, existing, sort; 674 | var at = options.at; 675 | var targetModel = this.model; 676 | var sortable = this.comparator && (at == null) && options.sort !== false; 677 | var sortAttr = _.isString(this.comparator) ? this.comparator : null; 678 | var toAdd = [], toRemove = [], modelMap = {}; 679 | var add = options.add, merge = options.merge, remove = options.remove; 680 | var order = !sortable && add && remove ? [] : false; 681 | 682 | // Turn bare objects into model references, and prevent invalid models 683 | // from being added. 684 | for (i = 0, l = models.length; i < l; i++) { 685 | attrs = models[i] || {}; 686 | if (attrs instanceof Model) { 687 | id = model = attrs; 688 | } else { 689 | id = attrs[targetModel.prototype.idAttribute || 'id']; 690 | } 691 | 692 | // If a duplicate is found, prevent it from being added and 693 | // optionally merge it into the existing model. 694 | if (existing = this.get(id)) { 695 | if (remove) modelMap[existing.cid] = true; 696 | if (merge) { 697 | attrs = attrs === model ? model.attributes : attrs; 698 | if (options.parse) attrs = existing.parse(attrs, options); 699 | existing.set(attrs, options); 700 | if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true; 701 | } 702 | models[i] = existing; 703 | 704 | // If this is a new, valid model, push it to the `toAdd` list. 705 | } else if (add) { 706 | model = models[i] = this._prepareModel(attrs, options); 707 | if (!model) continue; 708 | toAdd.push(model); 709 | this._addReference(model, options); 710 | } 711 | 712 | // Do not add multiple models with the same `id`. 713 | model = existing || model; 714 | if (order && (model.isNew() || !modelMap[model.id])) order.push(model); 715 | modelMap[model.id] = true; 716 | } 717 | 718 | // Remove nonexistent models if appropriate. 719 | if (remove) { 720 | for (i = 0, l = this.length; i < l; ++i) { 721 | if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model); 722 | } 723 | if (toRemove.length) this.remove(toRemove, options); 724 | } 725 | 726 | // See if sorting is needed, update `length` and splice in new models. 727 | if (toAdd.length || (order && order.length)) { 728 | if (sortable) sort = true; 729 | this.length += toAdd.length; 730 | if (at != null) { 731 | for (i = 0, l = toAdd.length; i < l; i++) { 732 | this.models.splice(at + i, 0, toAdd[i]); 733 | } 734 | } else { 735 | if (order) this.models.length = 0; 736 | var orderedModels = order || toAdd; 737 | for (i = 0, l = orderedModels.length; i < l; i++) { 738 | this.models.push(orderedModels[i]); 739 | } 740 | } 741 | } 742 | 743 | // Silently sort the collection if appropriate. 744 | if (sort) this.sort({silent: true}); 745 | 746 | // Unless silenced, it's time to fire all appropriate add/sort events. 747 | if (!options.silent) { 748 | for (i = 0, l = toAdd.length; i < l; i++) { 749 | (model = toAdd[i]).trigger('add', model, this, options); 750 | } 751 | if (sort || (order && order.length)) this.trigger('sort', this, options); 752 | } 753 | 754 | // Return the added (or merged) model (or models). 755 | return singular ? models[0] : models; 756 | }, 757 | 758 | // When you have more items than you want to add or remove individually, 759 | // you can reset the entire set with a new list of models, without firing 760 | // any granular `add` or `remove` events. Fires `reset` when finished. 761 | // Useful for bulk operations and optimizations. 762 | reset: function(models, options) { 763 | options || (options = {}); 764 | for (var i = 0, l = this.models.length; i < l; i++) { 765 | this._removeReference(this.models[i], options); 766 | } 767 | options.previousModels = this.models; 768 | this._reset(); 769 | models = this.add(models, _.extend({silent: true}, options)); 770 | if (!options.silent) this.trigger('reset', this, options); 771 | return models; 772 | }, 773 | 774 | // Add a model to the end of the collection. 775 | push: function(model, options) { 776 | return this.add(model, _.extend({at: this.length}, options)); 777 | }, 778 | 779 | // Remove a model from the end of the collection. 780 | pop: function(options) { 781 | var model = this.at(this.length - 1); 782 | this.remove(model, options); 783 | return model; 784 | }, 785 | 786 | // Add a model to the beginning of the collection. 787 | unshift: function(model, options) { 788 | return this.add(model, _.extend({at: 0}, options)); 789 | }, 790 | 791 | // Remove a model from the beginning of the collection. 792 | shift: function(options) { 793 | var model = this.at(0); 794 | this.remove(model, options); 795 | return model; 796 | }, 797 | 798 | // Slice out a sub-array of models from the collection. 799 | slice: function() { 800 | return slice.apply(this.models, arguments); 801 | }, 802 | 803 | // Get a model from the set by id. 804 | get: function(obj) { 805 | if (obj == null) return void 0; 806 | return this._byId[obj] || this._byId[obj.id] || this._byId[obj.cid]; 807 | }, 808 | 809 | // Get the model at the given index. 810 | at: function(index) { 811 | return this.models[index]; 812 | }, 813 | 814 | // Return models with matching attributes. Useful for simple cases of 815 | // `filter`. 816 | where: function(attrs, first) { 817 | if (_.isEmpty(attrs)) return first ? void 0 : []; 818 | return this[first ? 'find' : 'filter'](function(model) { 819 | for (var key in attrs) { 820 | if (attrs[key] !== model.get(key)) return false; 821 | } 822 | return true; 823 | }); 824 | }, 825 | 826 | // Return the first model with matching attributes. Useful for simple cases 827 | // of `find`. 828 | findWhere: function(attrs) { 829 | return this.where(attrs, true); 830 | }, 831 | 832 | // Force the collection to re-sort itself. You don't need to call this under 833 | // normal circumstances, as the set will maintain sort order as each item 834 | // is added. 835 | sort: function(options) { 836 | if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); 837 | options || (options = {}); 838 | 839 | // Run sort based on type of `comparator`. 840 | if (_.isString(this.comparator) || this.comparator.length === 1) { 841 | this.models = this.sortBy(this.comparator, this); 842 | } else { 843 | this.models.sort(_.bind(this.comparator, this)); 844 | } 845 | 846 | if (!options.silent) this.trigger('sort', this, options); 847 | return this; 848 | }, 849 | 850 | // Pluck an attribute from each model in the collection. 851 | pluck: function(attr) { 852 | return _.invoke(this.models, 'get', attr); 853 | }, 854 | 855 | // Fetch the default set of models for this collection, resetting the 856 | // collection when they arrive. If `reset: true` is passed, the response 857 | // data will be passed through the `reset` method instead of `set`. 858 | fetch: function(options) { 859 | options = options ? _.clone(options) : {}; 860 | if (options.parse === void 0) options.parse = true; 861 | var success = options.success; 862 | var collection = this; 863 | options.success = function(resp) { 864 | var method = options.reset ? 'reset' : 'set'; 865 | collection[method](resp, options); 866 | if (success) success(collection, resp, options); 867 | collection.trigger('sync', collection, resp, options); 868 | }; 869 | wrapError(this, options); 870 | return this.sync('read', this, options); 871 | }, 872 | 873 | // Create a new instance of a model in this collection. Add the model to the 874 | // collection immediately, unless `wait: true` is passed, in which case we 875 | // wait for the server to agree. 876 | create: function(model, options) { 877 | options = options ? _.clone(options) : {}; 878 | if (!(model = this._prepareModel(model, options))) return false; 879 | if (!options.wait) this.add(model, options); 880 | var collection = this; 881 | var success = options.success; 882 | options.success = function(model, resp) { 883 | if (options.wait) collection.add(model, options); 884 | if (success) success(model, resp, options); 885 | }; 886 | model.save(null, options); 887 | return model; 888 | }, 889 | 890 | // **parse** converts a response into a list of models to be added to the 891 | // collection. The default implementation is just to pass it through. 892 | parse: function(resp, options) { 893 | return resp; 894 | }, 895 | 896 | // Create a new collection with an identical list of models as this one. 897 | clone: function() { 898 | return new this.constructor(this.models); 899 | }, 900 | 901 | // Private method to reset all internal state. Called when the collection 902 | // is first initialized or reset. 903 | _reset: function() { 904 | this.length = 0; 905 | this.models = []; 906 | this._byId = {}; 907 | }, 908 | 909 | // Prepare a hash of attributes (or other model) to be added to this 910 | // collection. 911 | _prepareModel: function(attrs, options) { 912 | if (attrs instanceof Model) return attrs; 913 | options = options ? _.clone(options) : {}; 914 | options.collection = this; 915 | var model = new this.model(attrs, options); 916 | if (!model.validationError) return model; 917 | this.trigger('invalid', this, model.validationError, options); 918 | return false; 919 | }, 920 | 921 | // Internal method to create a model's ties to a collection. 922 | _addReference: function(model, options) { 923 | this._byId[model.cid] = model; 924 | if (model.id != null) this._byId[model.id] = model; 925 | if (!model.collection) model.collection = this; 926 | model.on('all', this._onModelEvent, this); 927 | }, 928 | 929 | // Internal method to sever a model's ties to a collection. 930 | _removeReference: function(model, options) { 931 | if (this === model.collection) delete model.collection; 932 | model.off('all', this._onModelEvent, this); 933 | }, 934 | 935 | // Internal method called every time a model in the set fires an event. 936 | // Sets need to update their indexes when models change ids. All other 937 | // events simply proxy through. "add" and "remove" events that originate 938 | // in other collections are ignored. 939 | _onModelEvent: function(event, model, collection, options) { 940 | if ((event === 'add' || event === 'remove') && collection !== this) return; 941 | if (event === 'destroy') this.remove(model, options); 942 | if (model && event === 'change:' + model.idAttribute) { 943 | delete this._byId[model.previous(model.idAttribute)]; 944 | if (model.id != null) this._byId[model.id] = model; 945 | } 946 | this.trigger.apply(this, arguments); 947 | } 948 | 949 | }); 950 | 951 | // Underscore methods that we want to implement on the Collection. 952 | // 90% of the core usefulness of Backbone Collections is actually implemented 953 | // right here: 954 | var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl', 955 | 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select', 956 | 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', 957 | 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest', 958 | 'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle', 959 | 'lastIndexOf', 'isEmpty', 'chain', 'sample']; 960 | 961 | // Mix in each Underscore method as a proxy to `Collection#models`. 962 | _.each(methods, function(method) { 963 | Collection.prototype[method] = function() { 964 | var args = slice.call(arguments); 965 | args.unshift(this.models); 966 | return _[method].apply(_, args); 967 | }; 968 | }); 969 | 970 | // Underscore methods that take a property name as an argument. 971 | var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy']; 972 | 973 | // Use attributes instead of properties. 974 | _.each(attributeMethods, function(method) { 975 | Collection.prototype[method] = function(value, context) { 976 | var iterator = _.isFunction(value) ? value : function(model) { 977 | return model.get(value); 978 | }; 979 | return _[method](this.models, iterator, context); 980 | }; 981 | }); 982 | 983 | // Backbone.View 984 | // ------------- 985 | 986 | // Backbone Views are almost more convention than they are actual code. A View 987 | // is simply a JavaScript object that represents a logical chunk of UI in the 988 | // DOM. This might be a single item, an entire list, a sidebar or panel, or 989 | // even the surrounding frame which wraps your whole app. Defining a chunk of 990 | // UI as a **View** allows you to define your DOM events declaratively, without 991 | // having to worry about render order ... and makes it easy for the view to 992 | // react to specific changes in the state of your models. 993 | 994 | // Creating a Backbone.View creates its initial element outside of the DOM, 995 | // if an existing element is not provided... 996 | var View = Backbone.View = function(options) { 997 | this.cid = _.uniqueId('view'); 998 | options || (options = {}); 999 | _.extend(this, _.pick(options, viewOptions)); 1000 | this._ensureElement(); 1001 | this.initialize.apply(this, arguments); 1002 | this.delegateEvents(); 1003 | }; 1004 | 1005 | // Cached regex to split keys for `delegate`. 1006 | var delegateEventSplitter = /^(\S+)\s*(.*)$/; 1007 | 1008 | // List of view options to be merged as properties. 1009 | var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; 1010 | 1011 | // Set up all inheritable **Backbone.View** properties and methods. 1012 | _.extend(View.prototype, Events, { 1013 | 1014 | // The default `tagName` of a View's element is `"div"`. 1015 | tagName: 'div', 1016 | 1017 | // jQuery delegate for element lookup, scoped to DOM elements within the 1018 | // current view. This should be preferred to global lookups where possible. 1019 | $: function(selector) { 1020 | return this.$el.find(selector); 1021 | }, 1022 | 1023 | // Initialize is an empty function by default. Override it with your own 1024 | // initialization logic. 1025 | initialize: function(){}, 1026 | 1027 | // **render** is the core function that your view should override, in order 1028 | // to populate its element (`this.el`), with the appropriate HTML. The 1029 | // convention is for **render** to always return `this`. 1030 | render: function() { 1031 | return this; 1032 | }, 1033 | 1034 | // Remove this view by taking the element out of the DOM, and removing any 1035 | // applicable Backbone.Events listeners. 1036 | remove: function() { 1037 | this.$el.remove(); 1038 | this.stopListening(); 1039 | return this; 1040 | }, 1041 | 1042 | // Change the view's element (`this.el` property), including event 1043 | // re-delegation. 1044 | setElement: function(element, delegate) { 1045 | if (this.$el) this.undelegateEvents(); 1046 | this.$el = element instanceof Backbone.$ ? element : Backbone.$(element); 1047 | this.el = this.$el[0]; 1048 | if (delegate !== false) this.delegateEvents(); 1049 | return this; 1050 | }, 1051 | 1052 | // Set callbacks, where `this.events` is a hash of 1053 | // 1054 | // *{"event selector": "callback"}* 1055 | // 1056 | // { 1057 | // 'mousedown .title': 'edit', 1058 | // 'click .button': 'save', 1059 | // 'click .open': function(e) { ... } 1060 | // } 1061 | // 1062 | // pairs. Callbacks will be bound to the view, with `this` set properly. 1063 | // Uses event delegation for efficiency. 1064 | // Omitting the selector binds the event to `this.el`. 1065 | // This only works for delegate-able events: not `focus`, `blur`, and 1066 | // not `change`, `submit`, and `reset` in Internet Explorer. 1067 | delegateEvents: function(events) { 1068 | if (!(events || (events = _.result(this, 'events')))) return this; 1069 | this.undelegateEvents(); 1070 | for (var key in events) { 1071 | var method = events[key]; 1072 | if (!_.isFunction(method)) method = this[events[key]]; 1073 | if (!method) continue; 1074 | 1075 | var match = key.match(delegateEventSplitter); 1076 | var eventName = match[1], selector = match[2]; 1077 | method = _.bind(method, this); 1078 | eventName += '.delegateEvents' + this.cid; 1079 | if (selector === '') { 1080 | this.$el.on(eventName, method); 1081 | } else { 1082 | this.$el.on(eventName, selector, method); 1083 | } 1084 | } 1085 | return this; 1086 | }, 1087 | 1088 | // Clears all callbacks previously bound to the view with `delegateEvents`. 1089 | // You usually don't need to use this, but may wish to if you have multiple 1090 | // Backbone views attached to the same DOM element. 1091 | undelegateEvents: function() { 1092 | this.$el.off('.delegateEvents' + this.cid); 1093 | return this; 1094 | }, 1095 | 1096 | // Ensure that the View has a DOM element to render into. 1097 | // If `this.el` is a string, pass it through `$()`, take the first 1098 | // matching element, and re-assign it to `el`. Otherwise, create 1099 | // an element from the `id`, `className` and `tagName` properties. 1100 | _ensureElement: function() { 1101 | if (!this.el) { 1102 | var attrs = _.extend({}, _.result(this, 'attributes')); 1103 | if (this.id) attrs.id = _.result(this, 'id'); 1104 | if (this.className) attrs['class'] = _.result(this, 'className'); 1105 | var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs); 1106 | this.setElement($el, false); 1107 | } else { 1108 | this.setElement(_.result(this, 'el'), false); 1109 | } 1110 | } 1111 | 1112 | }); 1113 | 1114 | // Backbone.sync 1115 | // ------------- 1116 | 1117 | // Override this function to change the manner in which Backbone persists 1118 | // models to the server. You will be passed the type of request, and the 1119 | // model in question. By default, makes a RESTful Ajax request 1120 | // to the model's `url()`. Some possible customizations could be: 1121 | // 1122 | // * Use `setTimeout` to batch rapid-fire updates into a single request. 1123 | // * Send up the models as XML instead of JSON. 1124 | // * Persist models via WebSockets instead of Ajax. 1125 | // 1126 | // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests 1127 | // as `POST`, with a `_method` parameter containing the true HTTP method, 1128 | // as well as all requests with the body as `application/x-www-form-urlencoded` 1129 | // instead of `application/json` with the model in a param named `model`. 1130 | // Useful when interfacing with server-side languages like **PHP** that make 1131 | // it difficult to read the body of `PUT` requests. 1132 | Backbone.sync = function(method, model, options) { 1133 | var type = methodMap[method]; 1134 | 1135 | // Default options, unless specified. 1136 | _.defaults(options || (options = {}), { 1137 | emulateHTTP: Backbone.emulateHTTP, 1138 | emulateJSON: Backbone.emulateJSON 1139 | }); 1140 | 1141 | // Default JSON-request options. 1142 | var params = {type: type, dataType: 'json'}; 1143 | 1144 | // Ensure that we have a URL. 1145 | if (!options.url) { 1146 | params.url = _.result(model, 'url') || urlError(); 1147 | } 1148 | 1149 | // Ensure that we have the appropriate request data. 1150 | if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { 1151 | params.contentType = 'application/json'; 1152 | params.data = JSON.stringify(options.attrs || model.toJSON(options)); 1153 | } 1154 | 1155 | // For older servers, emulate JSON by encoding the request into an HTML-form. 1156 | if (options.emulateJSON) { 1157 | params.contentType = 'application/x-www-form-urlencoded'; 1158 | params.data = params.data ? {model: params.data} : {}; 1159 | } 1160 | 1161 | // For older servers, emulate HTTP by mimicking the HTTP method with `_method` 1162 | // And an `X-HTTP-Method-Override` header. 1163 | if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { 1164 | params.type = 'POST'; 1165 | if (options.emulateJSON) params.data._method = type; 1166 | var beforeSend = options.beforeSend; 1167 | options.beforeSend = function(xhr) { 1168 | xhr.setRequestHeader('X-HTTP-Method-Override', type); 1169 | if (beforeSend) return beforeSend.apply(this, arguments); 1170 | }; 1171 | } 1172 | 1173 | // Don't process data on a non-GET request. 1174 | if (params.type !== 'GET' && !options.emulateJSON) { 1175 | params.processData = false; 1176 | } 1177 | 1178 | // If we're sending a `PATCH` request, and we're in an old Internet Explorer 1179 | // that still has ActiveX enabled by default, override jQuery to use that 1180 | // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8. 1181 | if (params.type === 'PATCH' && noXhrPatch) { 1182 | params.xhr = function() { 1183 | return new ActiveXObject("Microsoft.XMLHTTP"); 1184 | }; 1185 | } 1186 | 1187 | // Make the request, allowing the user to override any Ajax options. 1188 | var xhr = options.xhr = Backbone.ajax(_.extend(params, options)); 1189 | model.trigger('request', model, xhr, options); 1190 | return xhr; 1191 | }; 1192 | 1193 | var noXhrPatch = 1194 | typeof window !== 'undefined' && !!window.ActiveXObject && 1195 | !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent); 1196 | 1197 | // Map from CRUD to HTTP for our default `Backbone.sync` implementation. 1198 | var methodMap = { 1199 | 'create': 'POST', 1200 | 'update': 'PUT', 1201 | 'patch': 'PATCH', 1202 | 'delete': 'DELETE', 1203 | 'read': 'GET' 1204 | }; 1205 | 1206 | // Set the default implementation of `Backbone.ajax` to proxy through to `$`. 1207 | // Override this if you'd like to use a different library. 1208 | Backbone.ajax = function() { 1209 | return Backbone.$.ajax.apply(Backbone.$, arguments); 1210 | }; 1211 | 1212 | // Backbone.Router 1213 | // --------------- 1214 | 1215 | // Routers map faux-URLs to actions, and fire events when routes are 1216 | // matched. Creating a new one sets its `routes` hash, if not set statically. 1217 | var Router = Backbone.Router = function(options) { 1218 | options || (options = {}); 1219 | if (options.routes) this.routes = options.routes; 1220 | this._bindRoutes(); 1221 | this.initialize.apply(this, arguments); 1222 | }; 1223 | 1224 | // Cached regular expressions for matching named param parts and splatted 1225 | // parts of route strings. 1226 | var optionalParam = /\((.*?)\)/g; 1227 | var namedParam = /(\(\?)?:\w+/g; 1228 | var splatParam = /\*\w+/g; 1229 | var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; 1230 | 1231 | // Set up all inheritable **Backbone.Router** properties and methods. 1232 | _.extend(Router.prototype, Events, { 1233 | 1234 | // Initialize is an empty function by default. Override it with your own 1235 | // initialization logic. 1236 | initialize: function(){}, 1237 | 1238 | // Manually bind a single named route to a callback. For example: 1239 | // 1240 | // this.route('search/:query/p:num', 'search', function(query, num) { 1241 | // ... 1242 | // }); 1243 | // 1244 | route: function(route, name, callback) { 1245 | if (!_.isRegExp(route)) route = this._routeToRegExp(route); 1246 | if (_.isFunction(name)) { 1247 | callback = name; 1248 | name = ''; 1249 | } 1250 | if (!callback) callback = this[name]; 1251 | var router = this; 1252 | Backbone.history.route(route, function(fragment) { 1253 | var args = router._extractParameters(route, fragment); 1254 | router.execute(callback, args); 1255 | router.trigger.apply(router, ['route:' + name].concat(args)); 1256 | router.trigger('route', name, args); 1257 | Backbone.history.trigger('route', router, name, args); 1258 | }); 1259 | return this; 1260 | }, 1261 | 1262 | // Execute a route handler with the provided parameters. This is an 1263 | // excellent place to do pre-route setup or post-route cleanup. 1264 | execute: function(callback, args) { 1265 | if (callback) callback.apply(this, args); 1266 | }, 1267 | 1268 | // Simple proxy to `Backbone.history` to save a fragment into the history. 1269 | navigate: function(fragment, options) { 1270 | Backbone.history.navigate(fragment, options); 1271 | return this; 1272 | }, 1273 | 1274 | // Bind all defined routes to `Backbone.history`. We have to reverse the 1275 | // order of the routes here to support behavior where the most general 1276 | // routes can be defined at the bottom of the route map. 1277 | _bindRoutes: function() { 1278 | if (!this.routes) return; 1279 | this.routes = _.result(this, 'routes'); 1280 | var route, routes = _.keys(this.routes); 1281 | while ((route = routes.pop()) != null) { 1282 | this.route(route, this.routes[route]); 1283 | } 1284 | }, 1285 | 1286 | // Convert a route string into a regular expression, suitable for matching 1287 | // against the current location hash. 1288 | _routeToRegExp: function(route) { 1289 | route = route.replace(escapeRegExp, '\\$&') 1290 | .replace(optionalParam, '(?:$1)?') 1291 | .replace(namedParam, function(match, optional) { 1292 | return optional ? match : '([^/?]+)'; 1293 | }) 1294 | .replace(splatParam, '([^?]*?)'); 1295 | return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$'); 1296 | }, 1297 | 1298 | // Given a route, and a URL fragment that it matches, return the array of 1299 | // extracted decoded parameters. Empty or unmatched parameters will be 1300 | // treated as `null` to normalize cross-browser behavior. 1301 | _extractParameters: function(route, fragment) { 1302 | var params = route.exec(fragment).slice(1); 1303 | return _.map(params, function(param, i) { 1304 | // Don't decode the search params. 1305 | if (i === params.length - 1) return param || null; 1306 | return param ? decodeURIComponent(param) : null; 1307 | }); 1308 | } 1309 | 1310 | }); 1311 | 1312 | // Backbone.History 1313 | // ---------------- 1314 | 1315 | // Handles cross-browser history management, based on either 1316 | // [pushState](http://diveintohtml5.info/history.html) and real URLs, or 1317 | // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange) 1318 | // and URL fragments. If the browser supports neither (old IE, natch), 1319 | // falls back to polling. 1320 | var History = Backbone.History = function() { 1321 | this.handlers = []; 1322 | _.bindAll(this, 'checkUrl'); 1323 | 1324 | // Ensure that `History` can be used outside of the browser. 1325 | if (typeof window !== 'undefined') { 1326 | this.location = window.location; 1327 | this.history = window.history; 1328 | } 1329 | }; 1330 | 1331 | // Cached regex for stripping a leading hash/slash and trailing space. 1332 | var routeStripper = /^[#\/]|\s+$/g; 1333 | 1334 | // Cached regex for stripping leading and trailing slashes. 1335 | var rootStripper = /^\/+|\/+$/g; 1336 | 1337 | // Cached regex for detecting MSIE. 1338 | var isExplorer = /msie [\w.]+/; 1339 | 1340 | // Cached regex for removing a trailing slash. 1341 | var trailingSlash = /\/$/; 1342 | 1343 | // Cached regex for stripping urls of hash. 1344 | var pathStripper = /#.*$/; 1345 | 1346 | // Has the history handling already been started? 1347 | History.started = false; 1348 | 1349 | // Set up all inheritable **Backbone.History** properties and methods. 1350 | _.extend(History.prototype, Events, { 1351 | 1352 | // The default interval to poll for hash changes, if necessary, is 1353 | // twenty times a second. 1354 | interval: 50, 1355 | 1356 | // Are we at the app root? 1357 | atRoot: function() { 1358 | return this.location.pathname.replace(/[^\/]$/, '$&/') === this.root; 1359 | }, 1360 | 1361 | // Gets the true hash value. Cannot use location.hash directly due to bug 1362 | // in Firefox where location.hash will always be decoded. 1363 | getHash: function(window) { 1364 | var match = (window || this).location.href.match(/#(.*)$/); 1365 | return match ? match[1] : ''; 1366 | }, 1367 | 1368 | // Get the cross-browser normalized URL fragment, either from the URL, 1369 | // the hash, or the override. 1370 | getFragment: function(fragment, forcePushState) { 1371 | if (fragment == null) { 1372 | if (this._hasPushState || !this._wantsHashChange || forcePushState) { 1373 | fragment = decodeURI(this.location.pathname + this.location.search); 1374 | var root = this.root.replace(trailingSlash, ''); 1375 | if (!fragment.indexOf(root)) fragment = fragment.slice(root.length); 1376 | } else { 1377 | fragment = this.getHash(); 1378 | } 1379 | } 1380 | return fragment.replace(routeStripper, ''); 1381 | }, 1382 | 1383 | // Start the hash change handling, returning `true` if the current URL matches 1384 | // an existing route, and `false` otherwise. 1385 | start: function(options) { 1386 | if (History.started) throw new Error("Backbone.history has already been started"); 1387 | History.started = true; 1388 | 1389 | // Figure out the initial configuration. Do we need an iframe? 1390 | // Is pushState desired ... is it available? 1391 | this.options = _.extend({root: '/'}, this.options, options); 1392 | this.root = this.options.root; 1393 | this._wantsHashChange = this.options.hashChange !== false; 1394 | this._wantsPushState = !!this.options.pushState; 1395 | this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); 1396 | var fragment = this.getFragment(); 1397 | var docMode = document.documentMode; 1398 | var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); 1399 | 1400 | // Normalize root to always include a leading and trailing slash. 1401 | this.root = ('/' + this.root + '/').replace(rootStripper, '/'); 1402 | 1403 | if (oldIE && this._wantsHashChange) { 1404 | var frame = Backbone.$('