Merge lp:~trobz/web-addons/web-unleashed into lp:~webaddons-core-editors/web-addons/7.0

Proposed by Michel Meyer
Status: Needs review
Proposed branch: lp:~trobz/web-addons/web-unleashed
Merge into: lp:~webaddons-core-editors/web-addons/7.0
Diff against target: 34319 lines (+33875/-0)
72 files modified
web_unleashed/__init__.py (+2/-0)
web_unleashed/__openerp__.py (+82/-0)
web_unleashed/static/lib/backbone/backbone.js (+1581/-0)
web_unleashed/static/lib/jquery-addons/jquery.font_size.js (+11/-0)
web_unleashed/static/lib/jquery-addons/jquery.form_reset.js (+13/-0)
web_unleashed/static/lib/jquery-addons/jquery.serialize_object.js (+17/-0)
web_unleashed/static/lib/jquery-addons/jquery.when_all.js (+56/-0)
web_unleashed/static/lib/marionette/marionette.js (+2363/-0)
web_unleashed/static/lib/underscore-addons/underscore.deep_extend.js (+52/-0)
web_unleashed/static/lib/underscore-addons/underscore.find_index_where.js (+25/-0)
web_unleashed/static/lib/underscore/underscore.js (+1276/-0)
web_unleashed/static/src/css/pager.css (+4/-0)
web_unleashed/static/src/js/collections/base.js (+168/-0)
web_unleashed/static/src/js/collections/group.js (+236/-0)
web_unleashed/static/src/js/collections/iterator.js (+149/-0)
web_unleashed/static/src/js/collections/pager.js (+100/-0)
web_unleashed/static/src/js/controllers/pager.js (+402/-0)
web_unleashed/static/src/js/core/unleashed.js (+435/-0)
web_unleashed/static/src/js/models/base.js (+80/-0)
web_unleashed/static/src/js/models/iterator.js (+51/-0)
web_unleashed/static/src/js/models/query.js (+80/-0)
web_unleashed/static/src/js/models/state.js (+76/-0)
web_unleashed/static/src/js/utils/connector.js (+319/-0)
web_unleashed/static/src/js/utils/holder.js (+36/-0)
web_unleashed/static/src/js/views/base.js (+82/-0)
web_unleashed/static/src/js/views/pager.js (+124/-0)
web_unleashed/static/src/js/views/panel.js (+42/-0)
web_unleashed/static/src/js/views/region.js (+53/-0)
web_unleashed/static/src/js/views/unleashed.js (+246/-0)
web_unleashed/static/src/js/views/view.js (+19/-0)
web_unleashed/static/src/tests/connector.js (+240/-0)
web_unleashed/static/src/tests/group.js (+280/-0)
web_unleashed/static/src/tests/pager.js (+291/-0)
web_unleashed/static/src/xml/base.xml (+9/-0)
web_unleashed/static/src/xml/pager.xml (+41/-0)
web_unleashed/tests/__init__.py (+2/-0)
web_unleashed/tests/test_js.py (+35/-0)
web_unleashed_extra/__init__.py (+3/-0)
web_unleashed_extra/__openerp__.py (+76/-0)
web_unleashed_extra/static/lib/bootstrap-scoped/bootstrap-reset-openerp.css (+29/-0)
web_unleashed_extra/static/lib/bootstrap-scoped/bootstrap-scoped.css (+4689/-0)
web_unleashed_extra/static/lib/bootstrap-scoped/bootstrap.js (+2001/-0)
web_unleashed_extra/static/lib/font-awesome/css/font-awesome-ie7.css (+1203/-0)
web_unleashed_extra/static/lib/font-awesome/css/font-awesome-ie7.min.css (+384/-0)
web_unleashed_extra/static/lib/font-awesome/css/font-awesome.css (+1479/-0)
web_unleashed_extra/static/lib/font-awesome/css/font-awesome.min.css (+403/-0)
web_unleashed_extra/static/lib/font-awesome/font/fontawesome-webfont.svg (+399/-0)
web_unleashed_extra/static/lib/font-awesome/less/bootstrap.less (+84/-0)
web_unleashed_extra/static/lib/font-awesome/less/core.less (+129/-0)
web_unleashed_extra/static/lib/font-awesome/less/extras.less (+93/-0)
web_unleashed_extra/static/lib/font-awesome/less/font-awesome-ie7.less (+1953/-0)
web_unleashed_extra/static/lib/font-awesome/less/font-awesome.less (+33/-0)
web_unleashed_extra/static/lib/font-awesome/less/icons.less (+381/-0)
web_unleashed_extra/static/lib/font-awesome/less/mixins.less (+48/-0)
web_unleashed_extra/static/lib/font-awesome/less/path.less (+14/-0)
web_unleashed_extra/static/lib/font-awesome/less/variables.less (+735/-0)
web_unleashed_extra/static/lib/font-awesome/scss/_bootstrap.scss (+84/-0)
web_unleashed_extra/static/lib/font-awesome/scss/_core.scss (+129/-0)
web_unleashed_extra/static/lib/font-awesome/scss/_extras.scss (+93/-0)
web_unleashed_extra/static/lib/font-awesome/scss/_icons.scss (+381/-0)
web_unleashed_extra/static/lib/font-awesome/scss/_mixins.scss (+48/-0)
web_unleashed_extra/static/lib/font-awesome/scss/_path.scss (+14/-0)
web_unleashed_extra/static/lib/font-awesome/scss/_variables.scss (+734/-0)
web_unleashed_extra/static/lib/font-awesome/scss/font-awesome-ie7.scss (+1953/-0)
web_unleashed_extra/static/lib/font-awesome/scss/font-awesome.scss (+33/-0)
web_unleashed_extra/static/lib/moment-twix/twix.js (+2/-0)
web_unleashed_extra/static/lib/moment/moment.js (+6841/-0)
web_unleashed_extra/static/lib/numeral/numeral.js (+106/-0)
web_unleashed_extra/static/src/css/field_serialized.css (+28/-0)
web_unleashed_extra/static/src/css/global.css (+10/-0)
web_unleashed_extra/static/src/js/models/period.js (+86/-0)
web_unleashed_extra/static/src/js/widgets/field_serialized.js (+119/-0)
To merge this branch: bzr merge lp:~trobz/web-addons/web-unleashed
Reviewer Review Type Date Requested Status
Holger Brunn (Therp) Needs Resubmitting
Yannick Vaucher @ Camptocamp Abstain
Review via email: mp+195542@code.launchpad.net

Description of the change

New core module for an easy web module development:

- clear MVC pattern, based on Backbone and Marionnette... with all their documentations !
- new namespace to organize and get access to your objects
- full-featured Backbone Models with OpenERP JSON-RPC API support
 -QWeb rendering for Marionette views
- base objects to build custom views (Pager, Grouped Collection, Extended OpenERP View, State manager...)
 -unit tests for basic functionalities
- load/configuration commonly used libraries (momentjs, numeraljs, awesome-font,...)

Check the doc on https://github.com/trobz/openerp-web-unleashed

To post a comment you must log in.
Revision history for this message
Holger Brunn (Therp) (hbrunn) wrote :

just to inform you that I'm reading your code every now and then, but as it's a lot of it, a review will take time...

Revision history for this message
Michel Meyer (mmeyer-y) wrote :

Thanks for taking the time and feel free to ask me any questions :)

On 12/02/2013 09:02 PM, Holger Brunn (Therp) wrote:
> just to inform you that I'm reading your code every now and then, but as it's a lot of it, a review will take time...

Revision history for this message
Holger Brunn (Therp) (hbrunn) wrote :

Looks pretty good! I'm yet to try it in a serious project, but for the time being: Well done!

Some nits so far:

- your js tests will run twice, once from the web module, once triggered from tests/test_js.py. Is this possibly a leftover from development?

- any reason to deviate from putting qweb templates into static/src/xml?

- I understand the reasoning behind the name, but something more descriptive than web_unleashed would be better IMHO

- core/unleashed.js should use translated strings where appropriate

Now a serious question: Could you elaborate where the context you pass to sync() comes from? From my understanding, it's passed every time you'd call fetch() on the model, but where does that come from? UnleashedView gets it from the dataset (you shouldn't eval that then btw but a copy of it before passing it to the server in connector.js), which is fine, but I can't see where it's propagated further to the models? (I'm not a backbone expert if that's not obvious by now)

Revision history for this message
Michel Meyer (mmeyer-y) wrote :
Download full text (4.6 KiB)

Dear Holger,

It's an honor that you have looked at my code so deeply, glad to know
you're liking it :)

About your questions:

*- your js tests will run twice, once from the web module, once triggered from tests/test_js.py. Is this possibly a leftover from development?**
*
I did this because i want to launch my tests on Travis (for web unleashed sources on github), I think we can keep them as a "fast_suite".
Do you see any disadvantages to keep web unit test runnable on server side too ?

*- any reason to deviate from putting qweb templates into static/src/xml?**
*
I was not aware of community rules when I started this module, I will change it to be compliant with OpenERP rules.

*- I understand the reasoning behind the name, but something more descriptive than web_unleashed would be better IMHO**
*
I named it like this because it's my feeling when I'm using it.
The original web module on OpenERP is, at least, obscure and using well known libraries instead give so much advantages... (I'm still hope that OpenERP SA will go on this way one day...)

*- core/unleashed.js should use translated strings where appropriate
*
I don't see where there's strings to translate in the core, can you give me more details on this point ?
*
- Could you elaborate where the context you pass to sync() comes from? From my understanding, it's passed every time you'd call fetch() on the model, but where does that come from?**
**UnleashedView gets it from the dataset (you shouldn't eval that then btw but a copy of it before passing it to the server in connector.js), which is fine, but I can't see where it's propagated further to the models? (I'm not a backbone expert if that's not obvious by now)*

sync() is used by Backbone Model as a interface to achieve CRUD methods.
This function is called by Backbone with specific parameters (crud method, model/collection, options), so the js context at sync execution is the Backbone Model.

I use the Connector as an interface between Backbone models and the JSON-RPC API. For example, when fetch() is called, it will go through sync > connector > read, and the domain (filter), group by (group), order by (order), selected fields and the OpenERP context can be set on the "options" object and will be processed by the Connector.

sync() function should maybe set a default OpenERP context... but the context is only available at the OpenERP view level, not when sync() function is defined by web unleashed.
I think it's up to the developer to pass the context to the Backbone model, and then passing it to CRUD methods...
However we can imagine to add to BaseModel/BaseCollection a context option, if they have it, the model will pass it to CRUD methods automatically.

>*you shouldn't eval that then btw but a copy of it before passing it to the server in connector.js*

OK, but actually, I use the context only to get the user id and the language...
Maybe you can explain me what kind of side effects I can have by evaluating it in my view, at init ?

 From my understanding, the context is used only for view configuration on client side (get user id/language, some custom parameters, etc...).
Further, even if I don't pass the context to the serv...

Read more...

Revision history for this message
Holger Brunn (Therp) (hbrunn) wrote :

Michel, thanks for your comments. I already doubted my programming skills when I couldn't find out where the context is propagated, good to hear it's not.

On context: You definitely need to think of a way to pass the user's standard context (openerp.session.user_context) to your models. Otherwise, you lose stuff like the timezone (which causes all functions dealing with datetimes to assume UTC, and you really don't want that) and default values. That's what currently comes to my mind, there are also other things like the currently active project or the like.

On evaluating context: It can contain code line time(), so if you eval it on view initialization, you'll always pass the same time.

Translations: The messages in the Errors you throw are not translated to my understanding. Even though most of them look like they never should occur in a production environment, I still think it's good practice to translate them.

Tests: I don't see real world disadvantages, so if you've reason to keep them there, keep them

lp:~trobz/web-addons/web-unleashed updated
11. By Michel Meyer

[MERGE] GitHub changes (change files permission)

12. By Michel Meyer

rename templates folder into xml, to be compliant with OpenERP rules

13. By Michel Meyer

ensure a context can be passed on any JSON-RPC call made by backbone models

14. By Michel Meyer

remove this.context on UnleashedView (accessible with this.dataset.get_context())

15. By Michel Meyer

add a method to instantiate translated Error object + apply this method on all thrown errors

16. By Michel Meyer

fix mistakes after git > bzr merge...

Revision history for this message
Michel Meyer (mmeyer-y) wrote :
Download full text (4.3 KiB)

Hi Holger,

I did some changes on sources according to your comments, you can get
them on lp:~trobz/web-addons/web-unleashed
<https://code.launchpad.net/%7Etrobz/web-addons/web-unleashed> branch.

To resume my changes:
- 13
<http://bazaar.launchpad.net/%7Etrobz/web-addons/web-unleashed/revision/13>.
ensure a context can be passed on any JSON-RPC call made by backbone models
- 14
<http://bazaar.launchpad.net/%7Etrobz/web-addons/web-unleashed/revision/14>.
remove this.context on UnleashedView (accessible with
this.dataset.get_context())
- 15
<http://bazaar.launchpad.net/%7Etrobz/web-addons/web-unleashed/revision/15>.
add a method to instantiate translated Error object
- 12
<http://bazaar.launchpad.net/%7Etrobz/web-addons/web-unleashed/revision/12>.
rename template folder into xml

*Context*

I was not aware of all the implication of the context, thanks for all
these details ! It pushed me to look more deeply in OpenERP sources...
And after some research, this is what I understand about how OpenERP
manage the context internally:

/# for read queries
/
instance.web.Query generate a/compoundContext /based on multiple contexts:
- the user context (instance.session.user_context)
- the instance.web.Model.context, if any
- additional context specified for this query, if any (= options.context
on unleashed backbone models)
- re evaluate all these contexts together and generate the final one...
(really, don't ask me to look deeper in pyeval, seems so odd...)

# for count queries

instance.web.Query generate a/compoundContext /based on:
- the user context (instance.session.user_context)
- the instance.web.Model.context, if any
- additional context specified for this query, if any (= options.context
on unleashed backbone models)

This is done my calling this._model.context(this._context)}) at Query
execution.

/# for other method (create, update, delete)/
/
- /indirectly, in instance.web.JsonRPC core object, the user context is
set by default (if not context is passed as on options to call method)

It's done with:
_.defaults(params, {
     context: this.user_context || {}
});

I'm still not sure why OpenERP doesn't use the
instance.web.Model.context() method in instance.web.Model.call(), but
they may have a good reason to do so...

On unleashed code, at instance.web.Model instantiation in sync(), I pass
the options.context as the second parameter, so Model has a default
context used at execution for all type of query.

Finally, unleashed sync() function allow developers to pass a custom
context to instance.web.Model object, and the rest (user context,
etc...) is managed by OpenERP and I don't think there's extra work to do
on this...

*Error Translation**
*
Ok, I was thinking throwing errors is not made for the final user, it's
more for developers.

Nonetheless, I added a method on unleashed modules to instantiate a
translated Error object and I changed sources to use it on all error thrown.

Note: in OpenERP sources, at core level, Error are not translated, so we
may have a mix of translated/not translated error message...

It's a long email again, but I think the subject is interesting and
unleashed is made to be a ...

Read more...

Revision history for this message
Holger Brunn (Therp) (hbrunn) wrote :

Thanks for your changes concerning context, they seem fine to me.

Revision history for this message
Holger Brunn (Therp) (hbrunn) :
review: Approve
Revision history for this message
Yannick Vaucher @ Camptocamp (yvaucher-c2c) :
review: Abstain
Revision history for this message
Holger Brunn (Therp) (hbrunn) wrote :

This project is now hosted on https://github.com/OCA/web. Please move your proposal there. This guide may help you https://github.com/OCA/maintainers-tools/wiki/How-to-move-a-Merge-Proposal-to-GitHub

review: Needs Resubmitting

Unmerged revisions

16. By Michel Meyer

fix mistakes after git > bzr merge...

15. By Michel Meyer

add a method to instantiate translated Error object + apply this method on all thrown errors

14. By Michel Meyer

remove this.context on UnleashedView (accessible with this.dataset.get_context())

13. By Michel Meyer

ensure a context can be passed on any JSON-RPC call made by backbone models

12. By Michel Meyer

rename templates folder into xml, to be compliant with OpenERP rules

11. By Michel Meyer

[MERGE] GitHub changes (change files permission)

10. By Michel Meyer

[MERGE] GitHub web-unleashed modules with LP web-addons

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== added directory 'web_unleashed'
2=== added file 'web_unleashed/__init__.py'
3--- web_unleashed/__init__.py 1970-01-01 00:00:00 +0000
4+++ web_unleashed/__init__.py 2014-01-28 13:12:54 +0000
5@@ -0,0 +1,2 @@
6+# -*- coding: utf-8 -*-
7+import tests
8
9=== added file 'web_unleashed/__openerp__.py'
10--- web_unleashed/__openerp__.py 1970-01-01 00:00:00 +0000
11+++ web_unleashed/__openerp__.py 2014-01-28 13:12:54 +0000
12@@ -0,0 +1,82 @@
13+# -*- coding: utf-8 -*-
14+{
15+ 'name': 'Web Unleashed',
16+ 'version': '1.0',
17+ 'category': 'Hidden',
18+
19+ 'description': """
20+Core Web Module:
21+
22+- improve code architecture and organization
23+- add support of Backbone and Marionette frameworks
24+- native support of JSON-RPC API for Backbone
25+ """,
26+
27+ 'author': 'Trobz',
28+ 'website': 'https://github.com/trobz/openerp-web-unleashed',
29+
30+ 'depends': [
31+ 'web'
32+ ],
33+
34+ 'qweb' : [
35+ 'static/src/xml/*.xml',
36+ ],
37+
38+ 'css' : [
39+ 'static/src/css/pager.css',
40+ ],
41+
42+ 'js': [
43+ # backbone 1.1.0 and underscore 1.5.2 used in no conflict mode, see `unleashed.js` for more details
44+ 'static/lib/underscore/underscore.js',
45+ 'static/lib/backbone/backbone.js',
46+
47+ # backbone.marionette 1.1.0
48+ 'static/lib/marionette/marionette.js',
49+
50+ # addons for libs
51+ 'static/lib/jquery-addons/jquery.font_size.js',
52+ 'static/lib/jquery-addons/jquery.when_all.js',
53+ 'static/lib/jquery-addons/jquery.serialize_object.js',
54+ 'static/lib/jquery-addons/jquery.form_reset.js',
55+ 'static/lib/underscore-addons/underscore.deep_extend.js',
56+ 'static/lib/underscore-addons/underscore.find_index_where.js',
57+
58+ # manage object instanciation and sync support for backbone models
59+ 'static/src/js/core/unleashed.js',
60+
61+ # utils
62+ 'static/src/js/utils/holder.js',
63+ 'static/src/js/utils/connector.js',
64+
65+ # controller
66+ 'static/src/js/controllers/pager.js',
67+
68+ # backbone base models
69+ 'static/src/js/models/base.js',
70+ 'static/src/js/models/query.js',
71+ 'static/src/js/models/iterator.js',
72+ 'static/src/js/models/state.js',
73+
74+ # backbone base collections
75+ 'static/src/js/collections/base.js',
76+ 'static/src/js/collections/pager.js',
77+ 'static/src/js/collections/group.js',
78+ 'static/src/js/collections/iterator.js',
79+
80+ # backbone base views
81+ 'static/src/js/views/view.js',
82+ 'static/src/js/views/base.js',
83+ 'static/src/js/views/region.js',
84+ 'static/src/js/views/pager.js',
85+ 'static/src/js/views/panel.js',
86+ 'static/src/js/views/unleashed.js',
87+ ],
88+
89+ 'test': [
90+ 'static/src/tests/group.js',
91+ 'static/src/tests/pager.js',
92+ 'static/src/tests/connector.js',
93+ ]
94+}
95
96=== added directory 'web_unleashed/static'
97=== added directory 'web_unleashed/static/lib'
98=== added directory 'web_unleashed/static/lib/backbone'
99=== added file 'web_unleashed/static/lib/backbone/backbone.js'
100--- web_unleashed/static/lib/backbone/backbone.js 1970-01-01 00:00:00 +0000
101+++ web_unleashed/static/lib/backbone/backbone.js 2014-01-28 13:12:54 +0000
102@@ -0,0 +1,1581 @@
103+// Backbone.js 1.1.0
104+
105+// (c) 2010-2011 Jeremy Ashkenas, DocumentCloud Inc.
106+// (c) 2011-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
107+// Backbone may be freely distributed under the MIT license.
108+// For all details and documentation:
109+// http://backbonejs.org
110+
111+(function(){
112+
113+ // Initial Setup
114+ // -------------
115+
116+ // Save a reference to the global object (`window` in the browser, `exports`
117+ // on the server).
118+ var root = this;
119+
120+ // Save the previous value of the `Backbone` variable, so that it can be
121+ // restored later on, if `noConflict` is used.
122+ var previousBackbone = root.Backbone;
123+
124+ // Create local references to array methods we'll want to use later.
125+ var array = [];
126+ var push = array.push;
127+ var slice = array.slice;
128+ var splice = array.splice;
129+
130+ // The top-level namespace. All public Backbone classes and modules will
131+ // be attached to this. Exported for both the browser and the server.
132+ var Backbone;
133+ if (typeof exports !== 'undefined') {
134+ Backbone = exports;
135+ } else {
136+ Backbone = root.Backbone = {};
137+ }
138+
139+ // Current version of the library. Keep in sync with `package.json`.
140+ Backbone.VERSION = '1.1.0';
141+
142+ // Require Underscore, if we're on the server, and it's not already present.
143+ var _ = root._;
144+ if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
145+
146+ // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
147+ // the `$` variable.
148+ Backbone.$ = root.jQuery || root.Zepto || root.ender || root.$;
149+
150+ // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
151+ // to its previous owner. Returns a reference to this Backbone object.
152+ Backbone.noConflict = function() {
153+ root.Backbone = previousBackbone;
154+ return this;
155+ };
156+
157+ // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
158+ // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
159+ // set a `X-Http-Method-Override` header.
160+ Backbone.emulateHTTP = false;
161+
162+ // Turn on `emulateJSON` to support legacy servers that can't deal with direct
163+ // `application/json` requests ... will encode the body as
164+ // `application/x-www-form-urlencoded` instead and will send the model in a
165+ // form param named `model`.
166+ Backbone.emulateJSON = false;
167+
168+ // Backbone.Events
169+ // ---------------
170+
171+ // A module that can be mixed in to *any object* in order to provide it with
172+ // custom events. You may bind with `on` or remove with `off` callback
173+ // functions to an event; `trigger`-ing an event fires all callbacks in
174+ // succession.
175+ //
176+ // var object = {};
177+ // _.extend(object, Backbone.Events);
178+ // object.on('expand', function(){ alert('expanded'); });
179+ // object.trigger('expand');
180+ //
181+ var Events = Backbone.Events = {
182+
183+ // Bind an event to a `callback` function. Passing `"all"` will bind
184+ // the callback to all events fired.
185+ on: function(name, callback, context) {
186+ if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
187+ this._events || (this._events = {});
188+ var events = this._events[name] || (this._events[name] = []);
189+ events.push({callback: callback, context: context, ctx: context || this});
190+ return this;
191+ },
192+
193+ // Bind an event to only be triggered a single time. After the first time
194+ // the callback is invoked, it will be removed.
195+ once: function(name, callback, context) {
196+ if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
197+ var self = this;
198+ var once = _.once(function() {
199+ self.off(name, once);
200+ callback.apply(this, arguments);
201+ });
202+ once._callback = callback;
203+ return this.on(name, once, context);
204+ },
205+
206+ // Remove one or many callbacks. If `context` is null, removes all
207+ // callbacks with that function. If `callback` is null, removes all
208+ // callbacks for the event. If `name` is null, removes all bound
209+ // callbacks for all events.
210+ off: function(name, callback, context) {
211+ var retain, ev, events, names, i, l, j, k;
212+ if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
213+ if (!name && !callback && !context) {
214+ this._events = {};
215+ return this;
216+ }
217+ names = name ? [name] : _.keys(this._events);
218+ for (i = 0, l = names.length; i < l; i++) {
219+ name = names[i];
220+ if (events = this._events[name]) {
221+ this._events[name] = retain = [];
222+ if (callback || context) {
223+ for (j = 0, k = events.length; j < k; j++) {
224+ ev = events[j];
225+ if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
226+ (context && context !== ev.context)) {
227+ retain.push(ev);
228+ }
229+ }
230+ }
231+ if (!retain.length) delete this._events[name];
232+ }
233+ }
234+
235+ return this;
236+ },
237+
238+ // Trigger one or many events, firing all bound callbacks. Callbacks are
239+ // passed the same arguments as `trigger` is, apart from the event name
240+ // (unless you're listening on `"all"`, which will cause your callback to
241+ // receive the true name of the event as the first argument).
242+ trigger: function(name) {
243+ if (!this._events) return this;
244+ var args = slice.call(arguments, 1);
245+ if (!eventsApi(this, 'trigger', name, args)) return this;
246+ var events = this._events[name];
247+ var allEvents = this._events.all;
248+ if (events) triggerEvents(events, args);
249+ if (allEvents) triggerEvents(allEvents, arguments);
250+ return this;
251+ },
252+
253+ // Tell this object to stop listening to either specific events ... or
254+ // to every object it's currently listening to.
255+ stopListening: function(obj, name, callback) {
256+ var listeningTo = this._listeningTo;
257+ if (!listeningTo) return this;
258+ var remove = !name && !callback;
259+ if (!callback && typeof name === 'object') callback = this;
260+ if (obj) (listeningTo = {})[obj._listenId] = obj;
261+ for (var id in listeningTo) {
262+ obj = listeningTo[id];
263+ obj.off(name, callback, this);
264+ if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id];
265+ }
266+ return this;
267+ }
268+
269+ };
270+
271+ // Regular expression used to split event strings.
272+ var eventSplitter = /\s+/;
273+
274+ // Implement fancy features of the Events API such as multiple event
275+ // names `"change blur"` and jQuery-style event maps `{change: action}`
276+ // in terms of the existing API.
277+ var eventsApi = function(obj, action, name, rest) {
278+ if (!name) return true;
279+
280+ // Handle event maps.
281+ if (typeof name === 'object') {
282+ for (var key in name) {
283+ obj[action].apply(obj, [key, name[key]].concat(rest));
284+ }
285+ return false;
286+ }
287+
288+ // Handle space separated event names.
289+ if (eventSplitter.test(name)) {
290+ var names = name.split(eventSplitter);
291+ for (var i = 0, l = names.length; i < l; i++) {
292+ obj[action].apply(obj, [names[i]].concat(rest));
293+ }
294+ return false;
295+ }
296+
297+ return true;
298+ };
299+
300+ // A difficult-to-believe, but optimized internal dispatch function for
301+ // triggering events. Tries to keep the usual cases speedy (most internal
302+ // Backbone events have 3 arguments).
303+ var triggerEvents = function(events, args) {
304+ var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
305+ switch (args.length) {
306+ case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
307+ case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
308+ case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
309+ case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
310+ default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
311+ }
312+ };
313+
314+ var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
315+
316+ // Inversion-of-control versions of `on` and `once`. Tell *this* object to
317+ // listen to an event in another object ... keeping track of what it's
318+ // listening to.
319+ _.each(listenMethods, function(implementation, method) {
320+ Events[method] = function(obj, name, callback) {
321+ var listeningTo = this._listeningTo || (this._listeningTo = {});
322+ var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
323+ listeningTo[id] = obj;
324+ if (!callback && typeof name === 'object') callback = this;
325+ obj[implementation](name, callback, this);
326+ return this;
327+ };
328+ });
329+
330+ // Aliases for backwards compatibility.
331+ Events.bind = Events.on;
332+ Events.unbind = Events.off;
333+
334+ // Allow the `Backbone` object to serve as a global event bus, for folks who
335+ // want global "pubsub" in a convenient place.
336+ _.extend(Backbone, Events);
337+
338+ // Backbone.Model
339+ // --------------
340+
341+ // Backbone **Models** are the basic data object in the framework --
342+ // frequently representing a row in a table in a database on your server.
343+ // A discrete chunk of data and a bunch of useful, related methods for
344+ // performing computations and transformations on that data.
345+
346+ // Create a new model with the specified attributes. A client id (`cid`)
347+ // is automatically generated and assigned for you.
348+ var Model = Backbone.Model = function(attributes, options) {
349+ var attrs = attributes || {};
350+ options || (options = {});
351+ this.cid = _.uniqueId('c');
352+ this.attributes = {};
353+ if (options.collection) this.collection = options.collection;
354+ if (options.parse) attrs = this.parse(attrs, options) || {};
355+ attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
356+ this.set(attrs, options);
357+ this.changed = {};
358+ this.initialize.apply(this, arguments);
359+ };
360+
361+ // Attach all inheritable methods to the Model prototype.
362+ _.extend(Model.prototype, Events, {
363+
364+ // A hash of attributes whose current and previous value differ.
365+ changed: null,
366+
367+ // The value returned during the last failed validation.
368+ validationError: null,
369+
370+ // The default name for the JSON `id` attribute is `"id"`. MongoDB and
371+ // CouchDB users may want to set this to `"_id"`.
372+ idAttribute: 'id',
373+
374+ // Initialize is an empty function by default. Override it with your own
375+ // initialization logic.
376+ initialize: function(){},
377+
378+ // Return a copy of the model's `attributes` object.
379+ toJSON: function(options) {
380+ return _.clone(this.attributes);
381+ },
382+
383+ // Proxy `Backbone.sync` by default -- but override this if you need
384+ // custom syncing semantics for *this* particular model.
385+ sync: function() {
386+ return Backbone.sync.apply(this, arguments);
387+ },
388+
389+ // Get the value of an attribute.
390+ get: function(attr) {
391+ return this.attributes[attr];
392+ },
393+
394+ // Get the HTML-escaped value of an attribute.
395+ escape: function(attr) {
396+ return _.escape(this.get(attr));
397+ },
398+
399+ // Returns `true` if the attribute contains a value that is not null
400+ // or undefined.
401+ has: function(attr) {
402+ return this.get(attr) != null;
403+ },
404+
405+ // Set a hash of model attributes on the object, firing `"change"`. This is
406+ // the core primitive operation of a model, updating the data and notifying
407+ // anyone who needs to know about the change in state. The heart of the beast.
408+ set: function(key, val, options) {
409+ var attr, attrs, unset, changes, silent, changing, prev, current;
410+ if (key == null) return this;
411+
412+ // Handle both `"key", value` and `{key: value}` -style arguments.
413+ if (typeof key === 'object') {
414+ attrs = key;
415+ options = val;
416+ } else {
417+ (attrs = {})[key] = val;
418+ }
419+
420+ options || (options = {});
421+
422+ // Run validation.
423+ if (!this._validate(attrs, options)) return false;
424+
425+ // Extract attributes and options.
426+ unset = options.unset;
427+ silent = options.silent;
428+ changes = [];
429+ changing = this._changing;
430+ this._changing = true;
431+
432+ if (!changing) {
433+ this._previousAttributes = _.clone(this.attributes);
434+ this.changed = {};
435+ }
436+ current = this.attributes, prev = this._previousAttributes;
437+
438+ // Check for changes of `id`.
439+ if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
440+
441+ // For each `set` attribute, update or delete the current value.
442+ for (attr in attrs) {
443+ val = attrs[attr];
444+ if (!_.isEqual(current[attr], val)) changes.push(attr);
445+ if (!_.isEqual(prev[attr], val)) {
446+ this.changed[attr] = val;
447+ } else {
448+ delete this.changed[attr];
449+ }
450+ unset ? delete current[attr] : current[attr] = val;
451+ }
452+
453+ // Trigger all relevant attribute changes.
454+ if (!silent) {
455+ if (changes.length) this._pending = true;
456+ for (var i = 0, l = changes.length; i < l; i++) {
457+ this.trigger('change:' + changes[i], this, current[changes[i]], options);
458+ }
459+ }
460+
461+ // You might be wondering why there's a `while` loop here. Changes can
462+ // be recursively nested within `"change"` events.
463+ if (changing) return this;
464+ if (!silent) {
465+ while (this._pending) {
466+ this._pending = false;
467+ this.trigger('change', this, options);
468+ }
469+ }
470+ this._pending = false;
471+ this._changing = false;
472+ return this;
473+ },
474+
475+ // Remove an attribute from the model, firing `"change"`. `unset` is a noop
476+ // if the attribute doesn't exist.
477+ unset: function(attr, options) {
478+ return this.set(attr, void 0, _.extend({}, options, {unset: true}));
479+ },
480+
481+ // Clear all attributes on the model, firing `"change"`.
482+ clear: function(options) {
483+ var attrs = {};
484+ for (var key in this.attributes) attrs[key] = void 0;
485+ return this.set(attrs, _.extend({}, options, {unset: true}));
486+ },
487+
488+ // Determine if the model has changed since the last `"change"` event.
489+ // If you specify an attribute name, determine if that attribute has changed.
490+ hasChanged: function(attr) {
491+ if (attr == null) return !_.isEmpty(this.changed);
492+ return _.has(this.changed, attr);
493+ },
494+
495+ // Return an object containing all the attributes that have changed, or
496+ // false if there are no changed attributes. Useful for determining what
497+ // parts of a view need to be updated and/or what attributes need to be
498+ // persisted to the server. Unset attributes will be set to undefined.
499+ // You can also pass an attributes object to diff against the model,
500+ // determining if there *would be* a change.
501+ changedAttributes: function(diff) {
502+ if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
503+ var val, changed = false;
504+ var old = this._changing ? this._previousAttributes : this.attributes;
505+ for (var attr in diff) {
506+ if (_.isEqual(old[attr], (val = diff[attr]))) continue;
507+ (changed || (changed = {}))[attr] = val;
508+ }
509+ return changed;
510+ },
511+
512+ // Get the previous value of an attribute, recorded at the time the last
513+ // `"change"` event was fired.
514+ previous: function(attr) {
515+ if (attr == null || !this._previousAttributes) return null;
516+ return this._previousAttributes[attr];
517+ },
518+
519+ // Get all of the attributes of the model at the time of the previous
520+ // `"change"` event.
521+ previousAttributes: function() {
522+ return _.clone(this._previousAttributes);
523+ },
524+
525+ // Fetch the model from the server. If the server's representation of the
526+ // model differs from its current attributes, they will be overridden,
527+ // triggering a `"change"` event.
528+ fetch: function(options) {
529+ options = options ? _.clone(options) : {};
530+ if (options.parse === void 0) options.parse = true;
531+ var model = this;
532+ var success = options.success;
533+ options.success = function(resp) {
534+ if (!model.set(model.parse(resp, options), options)) return false;
535+ if (success) success(model, resp, options);
536+ model.trigger('sync', model, resp, options);
537+ };
538+ wrapError(this, options);
539+ return this.sync('read', this, options);
540+ },
541+
542+ // Set a hash of model attributes, and sync the model to the server.
543+ // If the server returns an attributes hash that differs, the model's
544+ // state will be `set` again.
545+ save: function(key, val, options) {
546+ var attrs, method, xhr, attributes = this.attributes;
547+
548+ // Handle both `"key", value` and `{key: value}` -style arguments.
549+ if (key == null || typeof key === 'object') {
550+ attrs = key;
551+ options = val;
552+ } else {
553+ (attrs = {})[key] = val;
554+ }
555+
556+ options = _.extend({validate: true}, options);
557+
558+ // If we're not waiting and attributes exist, save acts as
559+ // `set(attr).save(null, opts)` with validation. Otherwise, check if
560+ // the model will be valid when the attributes, if any, are set.
561+ if (attrs && !options.wait) {
562+ if (!this.set(attrs, options)) return false;
563+ } else {
564+ if (!this._validate(attrs, options)) return false;
565+ }
566+
567+ // Set temporary attributes if `{wait: true}`.
568+ if (attrs && options.wait) {
569+ this.attributes = _.extend({}, attributes, attrs);
570+ }
571+
572+ // After a successful server-side save, the client is (optionally)
573+ // updated with the server-side state.
574+ if (options.parse === void 0) options.parse = true;
575+ var model = this;
576+ var success = options.success;
577+ options.success = function(resp) {
578+ // Ensure attributes are restored during synchronous saves.
579+ model.attributes = attributes;
580+ var serverAttrs = model.parse(resp, options);
581+ if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
582+ if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
583+ return false;
584+ }
585+ if (success) success(model, resp, options);
586+ model.trigger('sync', model, resp, options);
587+ };
588+ wrapError(this, options);
589+
590+ method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
591+ if (method === 'patch') options.attrs = attrs;
592+ xhr = this.sync(method, this, options);
593+
594+ // Restore attributes.
595+ if (attrs && options.wait) this.attributes = attributes;
596+
597+ return xhr;
598+ },
599+
600+ // Destroy this model on the server if it was already persisted.
601+ // Optimistically removes the model from its collection, if it has one.
602+ // If `wait: true` is passed, waits for the server to respond before removal.
603+ destroy: function(options) {
604+ options = options ? _.clone(options) : {};
605+ var model = this;
606+ var success = options.success;
607+
608+ var destroy = function() {
609+ model.trigger('destroy', model, model.collection, options);
610+ };
611+
612+ options.success = function(resp) {
613+ if (options.wait || model.isNew()) destroy();
614+ if (success) success(model, resp, options);
615+ if (!model.isNew()) model.trigger('sync', model, resp, options);
616+ };
617+
618+ if (this.isNew()) {
619+ options.success();
620+ return false;
621+ }
622+ wrapError(this, options);
623+
624+ var xhr = this.sync('delete', this, options);
625+ if (!options.wait) destroy();
626+ return xhr;
627+ },
628+
629+ // Default URL for the model's representation on the server -- if you're
630+ // using Backbone's restful methods, override this to change the endpoint
631+ // that will be called.
632+ url: function() {
633+ var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
634+ if (this.isNew()) return base;
635+ return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
636+ },
637+
638+ // **parse** converts a response into the hash of attributes to be `set` on
639+ // the model. The default implementation is just to pass the response along.
640+ parse: function(resp, options) {
641+ return resp;
642+ },
643+
644+ // Create a new model with identical attributes to this one.
645+ clone: function() {
646+ return new this.constructor(this.attributes);
647+ },
648+
649+ // A model is new if it has never been saved to the server, and lacks an id.
650+ isNew: function() {
651+ return this.id == null;
652+ },
653+
654+ // Check if the model is currently in a valid state.
655+ isValid: function(options) {
656+ return this._validate({}, _.extend(options || {}, { validate: true }));
657+ },
658+
659+ // Run validation against the next complete set of model attributes,
660+ // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
661+ _validate: function(attrs, options) {
662+ if (!options.validate || !this.validate) return true;
663+ attrs = _.extend({}, this.attributes, attrs);
664+ var error = this.validationError = this.validate(attrs, options) || null;
665+ if (!error) return true;
666+ this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
667+ return false;
668+ }
669+
670+ });
671+
672+ // Underscore methods that we want to implement on the Model.
673+ var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
674+
675+ // Mix in each Underscore method as a proxy to `Model#attributes`.
676+ _.each(modelMethods, function(method) {
677+ Model.prototype[method] = function() {
678+ var args = slice.call(arguments);
679+ args.unshift(this.attributes);
680+ return _[method].apply(_, args);
681+ };
682+ });
683+
684+ // Backbone.Collection
685+ // -------------------
686+
687+ // If models tend to represent a single row of data, a Backbone Collection is
688+ // more analagous to a table full of data ... or a small slice or page of that
689+ // table, or a collection of rows that belong together for a particular reason
690+ // -- all of the messages in this particular folder, all of the documents
691+ // belonging to this particular author, and so on. Collections maintain
692+ // indexes of their models, both in order, and for lookup by `id`.
693+
694+ // Create a new **Collection**, perhaps to contain a specific type of `model`.
695+ // If a `comparator` is specified, the Collection will maintain
696+ // its models in sort order, as they're added and removed.
697+ var Collection = Backbone.Collection = function(models, options) {
698+ options || (options = {});
699+ if (options.model) this.model = options.model;
700+ if (options.comparator !== void 0) this.comparator = options.comparator;
701+ this._reset();
702+ this.initialize.apply(this, arguments);
703+ if (models) this.reset(models, _.extend({silent: true}, options));
704+ };
705+
706+ // Default options for `Collection#set`.
707+ var setOptions = {add: true, remove: true, merge: true};
708+ var addOptions = {add: true, remove: false};
709+
710+ // Define the Collection's inheritable methods.
711+ _.extend(Collection.prototype, Events, {
712+
713+ // The default model for a collection is just a **Backbone.Model**.
714+ // This should be overridden in most cases.
715+ model: Model,
716+
717+ // Initialize is an empty function by default. Override it with your own
718+ // initialization logic.
719+ initialize: function(){},
720+
721+ // The JSON representation of a Collection is an array of the
722+ // models' attributes.
723+ toJSON: function(options) {
724+ return this.map(function(model){ return model.toJSON(options); });
725+ },
726+
727+ // Proxy `Backbone.sync` by default.
728+ sync: function() {
729+ return Backbone.sync.apply(this, arguments);
730+ },
731+
732+ // Add a model, or list of models to the set.
733+ add: function(models, options) {
734+ return this.set(models, _.extend({merge: false}, options, addOptions));
735+ },
736+
737+ // Remove a model, or a list of models from the set.
738+ remove: function(models, options) {
739+ var singular = !_.isArray(models);
740+ models = singular ? [models] : _.clone(models);
741+ options || (options = {});
742+ var i, l, index, model;
743+ for (i = 0, l = models.length; i < l; i++) {
744+ model = models[i] = this.get(models[i]);
745+ if (!model) continue;
746+ delete this._byId[model.id];
747+ delete this._byId[model.cid];
748+ index = this.indexOf(model);
749+ this.models.splice(index, 1);
750+ this.length--;
751+ if (!options.silent) {
752+ options.index = index;
753+ model.trigger('remove', model, this, options);
754+ }
755+ this._removeReference(model);
756+ }
757+ return singular ? models[0] : models;
758+ },
759+
760+ // Update a collection by `set`-ing a new list of models, adding new ones,
761+ // removing models that are no longer present, and merging models that
762+ // already exist in the collection, as necessary. Similar to **Model#set**,
763+ // the core operation for updating the data contained by the collection.
764+ set: function(models, options) {
765+ options = _.defaults({}, options, setOptions);
766+ if (options.parse) models = this.parse(models, options);
767+ var singular = !_.isArray(models);
768+ models = singular ? (models ? [models] : []) : _.clone(models);
769+ var i, l, id, model, attrs, existing, sort;
770+ var at = options.at;
771+ var targetModel = this.model;
772+ var sortable = this.comparator && (at == null) && options.sort !== false;
773+ var sortAttr = _.isString(this.comparator) ? this.comparator : null;
774+ var toAdd = [], toRemove = [], modelMap = {};
775+ var add = options.add, merge = options.merge, remove = options.remove;
776+ var order = !sortable && add && remove ? [] : false;
777+
778+ // Turn bare objects into model references, and prevent invalid models
779+ // from being added.
780+ for (i = 0, l = models.length; i < l; i++) {
781+ attrs = models[i];
782+ if (attrs instanceof Model) {
783+ id = model = attrs;
784+ } else {
785+ id = attrs[targetModel.prototype.idAttribute];
786+ }
787+
788+ // If a duplicate is found, prevent it from being added and
789+ // optionally merge it into the existing model.
790+ if (existing = this.get(id)) {
791+ if (remove) modelMap[existing.cid] = true;
792+ if (merge) {
793+ attrs = attrs === model ? model.attributes : attrs;
794+ if (options.parse) attrs = existing.parse(attrs, options);
795+ existing.set(attrs, options);
796+ if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
797+ }
798+ models[i] = existing;
799+
800+ // If this is a new, valid model, push it to the `toAdd` list.
801+ } else if (add) {
802+ model = models[i] = this._prepareModel(attrs, options);
803+ if (!model) continue;
804+ toAdd.push(model);
805+
806+ // Listen to added models' events, and index models for lookup by
807+ // `id` and by `cid`.
808+ model.on('all', this._onModelEvent, this);
809+ this._byId[model.cid] = model;
810+ if (model.id != null) this._byId[model.id] = model;
811+ }
812+ if (order) order.push(existing || model);
813+ }
814+
815+ // Remove nonexistent models if appropriate.
816+ if (remove) {
817+ for (i = 0, l = this.length; i < l; ++i) {
818+ if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
819+ }
820+ if (toRemove.length) this.remove(toRemove, options);
821+ }
822+
823+ // See if sorting is needed, update `length` and splice in new models.
824+ if (toAdd.length || (order && order.length)) {
825+ if (sortable) sort = true;
826+ this.length += toAdd.length;
827+ if (at != null) {
828+ for (i = 0, l = toAdd.length; i < l; i++) {
829+ this.models.splice(at + i, 0, toAdd[i]);
830+ }
831+ } else {
832+ if (order) this.models.length = 0;
833+ var orderedModels = order || toAdd;
834+ for (i = 0, l = orderedModels.length; i < l; i++) {
835+ this.models.push(orderedModels[i]);
836+ }
837+ }
838+ }
839+
840+ // Silently sort the collection if appropriate.
841+ if (sort) this.sort({silent: true});
842+
843+ // Unless silenced, it's time to fire all appropriate add/sort events.
844+ if (!options.silent) {
845+ for (i = 0, l = toAdd.length; i < l; i++) {
846+ (model = toAdd[i]).trigger('add', model, this, options);
847+ }
848+ if (sort || (order && order.length)) this.trigger('sort', this, options);
849+ }
850+
851+ // Return the added (or merged) model (or models).
852+ return singular ? models[0] : models;
853+ },
854+
855+ // When you have more items than you want to add or remove individually,
856+ // you can reset the entire set with a new list of models, without firing
857+ // any granular `add` or `remove` events. Fires `reset` when finished.
858+ // Useful for bulk operations and optimizations.
859+ reset: function(models, options) {
860+ options || (options = {});
861+ for (var i = 0, l = this.models.length; i < l; i++) {
862+ this._removeReference(this.models[i]);
863+ }
864+ options.previousModels = this.models;
865+ this._reset();
866+ models = this.add(models, _.extend({silent: true}, options));
867+ if (!options.silent) this.trigger('reset', this, options);
868+ return models;
869+ },
870+
871+ // Add a model to the end of the collection.
872+ push: function(model, options) {
873+ return this.add(model, _.extend({at: this.length}, options));
874+ },
875+
876+ // Remove a model from the end of the collection.
877+ pop: function(options) {
878+ var model = this.at(this.length - 1);
879+ this.remove(model, options);
880+ return model;
881+ },
882+
883+ // Add a model to the beginning of the collection.
884+ unshift: function(model, options) {
885+ return this.add(model, _.extend({at: 0}, options));
886+ },
887+
888+ // Remove a model from the beginning of the collection.
889+ shift: function(options) {
890+ var model = this.at(0);
891+ this.remove(model, options);
892+ return model;
893+ },
894+
895+ // Slice out a sub-array of models from the collection.
896+ slice: function() {
897+ return slice.apply(this.models, arguments);
898+ },
899+
900+ // Get a model from the set by id.
901+ get: function(obj) {
902+ if (obj == null) return void 0;
903+ return this._byId[obj.id] || this._byId[obj.cid] || this._byId[obj];
904+ },
905+
906+ // Get the model at the given index.
907+ at: function(index) {
908+ return this.models[index];
909+ },
910+
911+ // Return models with matching attributes. Useful for simple cases of
912+ // `filter`.
913+ where: function(attrs, first) {
914+ if (_.isEmpty(attrs)) return first ? void 0 : [];
915+ return this[first ? 'find' : 'filter'](function(model) {
916+ for (var key in attrs) {
917+ if (attrs[key] !== model.get(key)) return false;
918+ }
919+ return true;
920+ });
921+ },
922+
923+ // Return the first model with matching attributes. Useful for simple cases
924+ // of `find`.
925+ findWhere: function(attrs) {
926+ return this.where(attrs, true);
927+ },
928+
929+ // Force the collection to re-sort itself. You don't need to call this under
930+ // normal circumstances, as the set will maintain sort order as each item
931+ // is added.
932+ sort: function(options) {
933+ if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
934+ options || (options = {});
935+
936+ // Run sort based on type of `comparator`.
937+ if (_.isString(this.comparator) || this.comparator.length === 1) {
938+ this.models = this.sortBy(this.comparator, this);
939+ } else {
940+ this.models.sort(_.bind(this.comparator, this));
941+ }
942+
943+ if (!options.silent) this.trigger('sort', this, options);
944+ return this;
945+ },
946+
947+ // Pluck an attribute from each model in the collection.
948+ pluck: function(attr) {
949+ return _.invoke(this.models, 'get', attr);
950+ },
951+
952+ // Fetch the default set of models for this collection, resetting the
953+ // collection when they arrive. If `reset: true` is passed, the response
954+ // data will be passed through the `reset` method instead of `set`.
955+ fetch: function(options) {
956+ options = options ? _.clone(options) : {};
957+ if (options.parse === void 0) options.parse = true;
958+ var success = options.success;
959+ var collection = this;
960+ options.success = function(resp) {
961+ var method = options.reset ? 'reset' : 'set';
962+ collection[method](resp, options);
963+ if (success) success(collection, resp, options);
964+ collection.trigger('sync', collection, resp, options);
965+ };
966+ wrapError(this, options);
967+ return this.sync('read', this, options);
968+ },
969+
970+ // Create a new instance of a model in this collection. Add the model to the
971+ // collection immediately, unless `wait: true` is passed, in which case we
972+ // wait for the server to agree.
973+ create: function(model, options) {
974+ options = options ? _.clone(options) : {};
975+ if (!(model = this._prepareModel(model, options))) return false;
976+ if (!options.wait) this.add(model, options);
977+ var collection = this;
978+ var success = options.success;
979+ options.success = function(model, resp, options) {
980+ if (options.wait) collection.add(model, options);
981+ if (success) success(model, resp, options);
982+ };
983+ model.save(null, options);
984+ return model;
985+ },
986+
987+ // **parse** converts a response into a list of models to be added to the
988+ // collection. The default implementation is just to pass it through.
989+ parse: function(resp, options) {
990+ return resp;
991+ },
992+
993+ // Create a new collection with an identical list of models as this one.
994+ clone: function() {
995+ return new this.constructor(this.models);
996+ },
997+
998+ // Private method to reset all internal state. Called when the collection
999+ // is first initialized or reset.
1000+ _reset: function() {
1001+ this.length = 0;
1002+ this.models = [];
1003+ this._byId = {};
1004+ },
1005+
1006+ // Prepare a hash of attributes (or other model) to be added to this
1007+ // collection.
1008+ _prepareModel: function(attrs, options) {
1009+ if (attrs instanceof Model) {
1010+ if (!attrs.collection) attrs.collection = this;
1011+ return attrs;
1012+ }
1013+ options = options ? _.clone(options) : {};
1014+ options.collection = this;
1015+ var model = new this.model(attrs, options);
1016+ if (!model.validationError) return model;
1017+ this.trigger('invalid', this, model.validationError, options);
1018+ return false;
1019+ },
1020+
1021+ // Internal method to sever a model's ties to a collection.
1022+ _removeReference: function(model) {
1023+ if (this === model.collection) delete model.collection;
1024+ model.off('all', this._onModelEvent, this);
1025+ },
1026+
1027+ // Internal method called every time a model in the set fires an event.
1028+ // Sets need to update their indexes when models change ids. All other
1029+ // events simply proxy through. "add" and "remove" events that originate
1030+ // in other collections are ignored.
1031+ _onModelEvent: function(event, model, collection, options) {
1032+ if ((event === 'add' || event === 'remove') && collection !== this) return;
1033+ if (event === 'destroy') this.remove(model, options);
1034+ if (model && event === 'change:' + model.idAttribute) {
1035+ delete this._byId[model.previous(model.idAttribute)];
1036+ if (model.id != null) this._byId[model.id] = model;
1037+ }
1038+ this.trigger.apply(this, arguments);
1039+ }
1040+
1041+ });
1042+
1043+ // Underscore methods that we want to implement on the Collection.
1044+ // 90% of the core usefulness of Backbone Collections is actually implemented
1045+ // right here:
1046+ var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
1047+ 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
1048+ 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
1049+ 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
1050+ 'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle',
1051+ 'lastIndexOf', 'isEmpty', 'chain'];
1052+
1053+ // Mix in each Underscore method as a proxy to `Collection#models`.
1054+ _.each(methods, function(method) {
1055+ Collection.prototype[method] = function() {
1056+ var args = slice.call(arguments);
1057+ args.unshift(this.models);
1058+ return _[method].apply(_, args);
1059+ };
1060+ });
1061+
1062+ // Underscore methods that take a property name as an argument.
1063+ var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
1064+
1065+ // Use attributes instead of properties.
1066+ _.each(attributeMethods, function(method) {
1067+ Collection.prototype[method] = function(value, context) {
1068+ var iterator = _.isFunction(value) ? value : function(model) {
1069+ return model.get(value);
1070+ };
1071+ return _[method](this.models, iterator, context);
1072+ };
1073+ });
1074+
1075+ // Backbone.View
1076+ // -------------
1077+
1078+ // Backbone Views are almost more convention than they are actual code. A View
1079+ // is simply a JavaScript object that represents a logical chunk of UI in the
1080+ // DOM. This might be a single item, an entire list, a sidebar or panel, or
1081+ // even the surrounding frame which wraps your whole app. Defining a chunk of
1082+ // UI as a **View** allows you to define your DOM events declaratively, without
1083+ // having to worry about render order ... and makes it easy for the view to
1084+ // react to specific changes in the state of your models.
1085+
1086+ // Creating a Backbone.View creates its initial element outside of the DOM,
1087+ // if an existing element is not provided...
1088+ var View = Backbone.View = function(options) {
1089+ this.cid = _.uniqueId('view');
1090+ options || (options = {});
1091+ _.extend(this, _.pick(options, viewOptions));
1092+ this._ensureElement();
1093+ this.initialize.apply(this, arguments);
1094+ this.delegateEvents();
1095+ };
1096+
1097+ // Cached regex to split keys for `delegate`.
1098+ var delegateEventSplitter = /^(\S+)\s*(.*)$/;
1099+
1100+ // List of view options to be merged as properties.
1101+ var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
1102+
1103+ // Set up all inheritable **Backbone.View** properties and methods.
1104+ _.extend(View.prototype, Events, {
1105+
1106+ // The default `tagName` of a View's element is `"div"`.
1107+ tagName: 'div',
1108+
1109+ // jQuery delegate for element lookup, scoped to DOM elements within the
1110+ // current view. This should be preferred to global lookups where possible.
1111+ $: function(selector) {
1112+ return this.$el.find(selector);
1113+ },
1114+
1115+ // Initialize is an empty function by default. Override it with your own
1116+ // initialization logic.
1117+ initialize: function(){},
1118+
1119+ // **render** is the core function that your view should override, in order
1120+ // to populate its element (`this.el`), with the appropriate HTML. The
1121+ // convention is for **render** to always return `this`.
1122+ render: function() {
1123+ return this;
1124+ },
1125+
1126+ // Remove this view by taking the element out of the DOM, and removing any
1127+ // applicable Backbone.Events listeners.
1128+ remove: function() {
1129+ this.$el.remove();
1130+ this.stopListening();
1131+ return this;
1132+ },
1133+
1134+ // Change the view's element (`this.el` property), including event
1135+ // re-delegation.
1136+ setElement: function(element, delegate) {
1137+ if (this.$el) this.undelegateEvents();
1138+ this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
1139+ this.el = this.$el[0];
1140+ if (delegate !== false) this.delegateEvents();
1141+ return this;
1142+ },
1143+
1144+ // Set callbacks, where `this.events` is a hash of
1145+ //
1146+ // *{"event selector": "callback"}*
1147+ //
1148+ // {
1149+ // 'mousedown .title': 'edit',
1150+ // 'click .button': 'save',
1151+ // 'click .open': function(e) { ... }
1152+ // }
1153+ //
1154+ // pairs. Callbacks will be bound to the view, with `this` set properly.
1155+ // Uses event delegation for efficiency.
1156+ // Omitting the selector binds the event to `this.el`.
1157+ // This only works for delegate-able events: not `focus`, `blur`, and
1158+ // not `change`, `submit`, and `reset` in Internet Explorer.
1159+ delegateEvents: function(events) {
1160+ if (!(events || (events = _.result(this, 'events')))) return this;
1161+ this.undelegateEvents();
1162+ for (var key in events) {
1163+ var method = events[key];
1164+ if (!_.isFunction(method)) method = this[events[key]];
1165+ if (!method) continue;
1166+
1167+ var match = key.match(delegateEventSplitter);
1168+ var eventName = match[1], selector = match[2];
1169+ method = _.bind(method, this);
1170+ eventName += '.delegateEvents' + this.cid;
1171+ if (selector === '') {
1172+ this.$el.on(eventName, method);
1173+ } else {
1174+ this.$el.on(eventName, selector, method);
1175+ }
1176+ }
1177+ return this;
1178+ },
1179+
1180+ // Clears all callbacks previously bound to the view with `delegateEvents`.
1181+ // You usually don't need to use this, but may wish to if you have multiple
1182+ // Backbone views attached to the same DOM element.
1183+ undelegateEvents: function() {
1184+ this.$el.off('.delegateEvents' + this.cid);
1185+ return this;
1186+ },
1187+
1188+ // Ensure that the View has a DOM element to render into.
1189+ // If `this.el` is a string, pass it through `$()`, take the first
1190+ // matching element, and re-assign it to `el`. Otherwise, create
1191+ // an element from the `id`, `className` and `tagName` properties.
1192+ _ensureElement: function() {
1193+ if (!this.el) {
1194+ var attrs = _.extend({}, _.result(this, 'attributes'));
1195+ if (this.id) attrs.id = _.result(this, 'id');
1196+ if (this.className) attrs['class'] = _.result(this, 'className');
1197+ var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
1198+ this.setElement($el, false);
1199+ } else {
1200+ this.setElement(_.result(this, 'el'), false);
1201+ }
1202+ }
1203+
1204+ });
1205+
1206+ // Backbone.sync
1207+ // -------------
1208+
1209+ // Override this function to change the manner in which Backbone persists
1210+ // models to the server. You will be passed the type of request, and the
1211+ // model in question. By default, makes a RESTful Ajax request
1212+ // to the model's `url()`. Some possible customizations could be:
1213+ //
1214+ // * Use `setTimeout` to batch rapid-fire updates into a single request.
1215+ // * Send up the models as XML instead of JSON.
1216+ // * Persist models via WebSockets instead of Ajax.
1217+ //
1218+ // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
1219+ // as `POST`, with a `_method` parameter containing the true HTTP method,
1220+ // as well as all requests with the body as `application/x-www-form-urlencoded`
1221+ // instead of `application/json` with the model in a param named `model`.
1222+ // Useful when interfacing with server-side languages like **PHP** that make
1223+ // it difficult to read the body of `PUT` requests.
1224+ Backbone.sync = function(method, model, options) {
1225+ var type = methodMap[method];
1226+
1227+ // Default options, unless specified.
1228+ _.defaults(options || (options = {}), {
1229+ emulateHTTP: Backbone.emulateHTTP,
1230+ emulateJSON: Backbone.emulateJSON
1231+ });
1232+
1233+ // Default JSON-request options.
1234+ var params = {type: type, dataType: 'json'};
1235+
1236+ // Ensure that we have a URL.
1237+ if (!options.url) {
1238+ params.url = _.result(model, 'url') || urlError();
1239+ }
1240+
1241+ // Ensure that we have the appropriate request data.
1242+ if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
1243+ params.contentType = 'application/json';
1244+ params.data = JSON.stringify(options.attrs || model.toJSON(options));
1245+ }
1246+
1247+ // For older servers, emulate JSON by encoding the request into an HTML-form.
1248+ if (options.emulateJSON) {
1249+ params.contentType = 'application/x-www-form-urlencoded';
1250+ params.data = params.data ? {model: params.data} : {};
1251+ }
1252+
1253+ // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
1254+ // And an `X-HTTP-Method-Override` header.
1255+ if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
1256+ params.type = 'POST';
1257+ if (options.emulateJSON) params.data._method = type;
1258+ var beforeSend = options.beforeSend;
1259+ options.beforeSend = function(xhr) {
1260+ xhr.setRequestHeader('X-HTTP-Method-Override', type);
1261+ if (beforeSend) return beforeSend.apply(this, arguments);
1262+ };
1263+ }
1264+
1265+ // Don't process data on a non-GET request.
1266+ if (params.type !== 'GET' && !options.emulateJSON) {
1267+ params.processData = false;
1268+ }
1269+
1270+ // If we're sending a `PATCH` request, and we're in an old Internet Explorer
1271+ // that still has ActiveX enabled by default, override jQuery to use that
1272+ // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8.
1273+ if (params.type === 'PATCH' && noXhrPatch) {
1274+ params.xhr = function() {
1275+ return new ActiveXObject("Microsoft.XMLHTTP");
1276+ };
1277+ }
1278+
1279+ // Make the request, allowing the user to override any Ajax options.
1280+ var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
1281+ model.trigger('request', model, xhr, options);
1282+ return xhr;
1283+ };
1284+
1285+ var noXhrPatch = typeof window !== 'undefined' && !!window.ActiveXObject && !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent);
1286+
1287+ // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
1288+ var methodMap = {
1289+ 'create': 'POST',
1290+ 'update': 'PUT',
1291+ 'patch': 'PATCH',
1292+ 'delete': 'DELETE',
1293+ 'read': 'GET'
1294+ };
1295+
1296+ // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
1297+ // Override this if you'd like to use a different library.
1298+ Backbone.ajax = function() {
1299+ return Backbone.$.ajax.apply(Backbone.$, arguments);
1300+ };
1301+
1302+ // Backbone.Router
1303+ // ---------------
1304+
1305+ // Routers map faux-URLs to actions, and fire events when routes are
1306+ // matched. Creating a new one sets its `routes` hash, if not set statically.
1307+ var Router = Backbone.Router = function(options) {
1308+ options || (options = {});
1309+ if (options.routes) this.routes = options.routes;
1310+ this._bindRoutes();
1311+ this.initialize.apply(this, arguments);
1312+ };
1313+
1314+ // Cached regular expressions for matching named param parts and splatted
1315+ // parts of route strings.
1316+ var optionalParam = /\((.*?)\)/g;
1317+ var namedParam = /(\(\?)?:\w+/g;
1318+ var splatParam = /\*\w+/g;
1319+ var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
1320+
1321+ // Set up all inheritable **Backbone.Router** properties and methods.
1322+ _.extend(Router.prototype, Events, {
1323+
1324+ // Initialize is an empty function by default. Override it with your own
1325+ // initialization logic.
1326+ initialize: function(){},
1327+
1328+ // Manually bind a single named route to a callback. For example:
1329+ //
1330+ // this.route('search/:query/p:num', 'search', function(query, num) {
1331+ // ...
1332+ // });
1333+ //
1334+ route: function(route, name, callback) {
1335+ if (!_.isRegExp(route)) route = this._routeToRegExp(route);
1336+ if (_.isFunction(name)) {
1337+ callback = name;
1338+ name = '';
1339+ }
1340+ if (!callback) callback = this[name];
1341+ var router = this;
1342+ Backbone.history.route(route, function(fragment) {
1343+ var args = router._extractParameters(route, fragment);
1344+ callback && callback.apply(router, args);
1345+ router.trigger.apply(router, ['route:' + name].concat(args));
1346+ router.trigger('route', name, args);
1347+ Backbone.history.trigger('route', router, name, args);
1348+ });
1349+ return this;
1350+ },
1351+
1352+ // Simple proxy to `Backbone.history` to save a fragment into the history.
1353+ navigate: function(fragment, options) {
1354+ Backbone.history.navigate(fragment, options);
1355+ return this;
1356+ },
1357+
1358+ // Bind all defined routes to `Backbone.history`. We have to reverse the
1359+ // order of the routes here to support behavior where the most general
1360+ // routes can be defined at the bottom of the route map.
1361+ _bindRoutes: function() {
1362+ if (!this.routes) return;
1363+ this.routes = _.result(this, 'routes');
1364+ var route, routes = _.keys(this.routes);
1365+ while ((route = routes.pop()) != null) {
1366+ this.route(route, this.routes[route]);
1367+ }
1368+ },
1369+
1370+ // Convert a route string into a regular expression, suitable for matching
1371+ // against the current location hash.
1372+ _routeToRegExp: function(route) {
1373+ route = route.replace(escapeRegExp, '\\$&')
1374+ .replace(optionalParam, '(?:$1)?')
1375+ .replace(namedParam, function(match, optional) {
1376+ return optional ? match : '([^\/]+)';
1377+ })
1378+ .replace(splatParam, '(.*?)');
1379+ return new RegExp('^' + route + '$');
1380+ },
1381+
1382+ // Given a route, and a URL fragment that it matches, return the array of
1383+ // extracted decoded parameters. Empty or unmatched parameters will be
1384+ // treated as `null` to normalize cross-browser behavior.
1385+ _extractParameters: function(route, fragment) {
1386+ var params = route.exec(fragment).slice(1);
1387+ return _.map(params, function(param) {
1388+ return param ? decodeURIComponent(param) : null;
1389+ });
1390+ }
1391+
1392+ });
1393+
1394+ // Backbone.History
1395+ // ----------------
1396+
1397+ // Handles cross-browser history management, based on either
1398+ // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
1399+ // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
1400+ // and URL fragments. If the browser supports neither (old IE, natch),
1401+ // falls back to polling.
1402+ var History = Backbone.History = function() {
1403+ this.handlers = [];
1404+ _.bindAll(this, 'checkUrl');
1405+
1406+ // Ensure that `History` can be used outside of the browser.
1407+ if (typeof window !== 'undefined') {
1408+ this.location = window.location;
1409+ this.history = window.history;
1410+ }
1411+ };
1412+
1413+ // Cached regex for stripping a leading hash/slash and trailing space.
1414+ var routeStripper = /^[#\/]|\s+$/g;
1415+
1416+ // Cached regex for stripping leading and trailing slashes.
1417+ var rootStripper = /^\/+|\/+$/g;
1418+
1419+ // Cached regex for detecting MSIE.
1420+ var isExplorer = /msie [\w.]+/;
1421+
1422+ // Cached regex for removing a trailing slash.
1423+ var trailingSlash = /\/$/;
1424+
1425+ // Cached regex for stripping urls of hash and query.
1426+ var pathStripper = /[?#].*$/;
1427+
1428+ // Has the history handling already been started?
1429+ History.started = false;
1430+
1431+ // Set up all inheritable **Backbone.History** properties and methods.
1432+ _.extend(History.prototype, Events, {
1433+
1434+ // The default interval to poll for hash changes, if necessary, is
1435+ // twenty times a second.
1436+ interval: 50,
1437+
1438+ // Gets the true hash value. Cannot use location.hash directly due to bug
1439+ // in Firefox where location.hash will always be decoded.
1440+ getHash: function(window) {
1441+ var match = (window || this).location.href.match(/#(.*)$/);
1442+ return match ? match[1] : '';
1443+ },
1444+
1445+ // Get the cross-browser normalized URL fragment, either from the URL,
1446+ // the hash, or the override.
1447+ getFragment: function(fragment, forcePushState) {
1448+ if (fragment == null) {
1449+ if (this._hasPushState || !this._wantsHashChange || forcePushState) {
1450+ fragment = this.location.pathname;
1451+ var root = this.root.replace(trailingSlash, '');
1452+ if (!fragment.indexOf(root)) fragment = fragment.slice(root.length);
1453+ } else {
1454+ fragment = this.getHash();
1455+ }
1456+ }
1457+ return fragment.replace(routeStripper, '');
1458+ },
1459+
1460+ // Start the hash change handling, returning `true` if the current URL matches
1461+ // an existing route, and `false` otherwise.
1462+ start: function(options) {
1463+ if (History.started) throw new Error("Backbone.history has already been started");
1464+ History.started = true;
1465+
1466+ // Figure out the initial configuration. Do we need an iframe?
1467+ // Is pushState desired ... is it available?
1468+ this.options = _.extend({root: '/'}, this.options, options);
1469+ this.root = this.options.root;
1470+ this._wantsHashChange = this.options.hashChange !== false;
1471+ this._wantsPushState = !!this.options.pushState;
1472+ this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
1473+ var fragment = this.getFragment();
1474+ var docMode = document.documentMode;
1475+ var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
1476+
1477+ // Normalize root to always include a leading and trailing slash.
1478+ this.root = ('/' + this.root + '/').replace(rootStripper, '/');
1479+
1480+ if (oldIE && this._wantsHashChange) {
1481+ this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
1482+ this.navigate(fragment);
1483+ }
1484+
1485+ // Depending on whether we're using pushState or hashes, and whether
1486+ // 'onhashchange' is supported, determine how we check the URL state.
1487+ if (this._hasPushState) {
1488+ Backbone.$(window).on('popstate', this.checkUrl);
1489+ } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
1490+ Backbone.$(window).on('hashchange', this.checkUrl);
1491+ } else if (this._wantsHashChange) {
1492+ this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
1493+ }
1494+
1495+ // Determine if we need to change the base url, for a pushState link
1496+ // opened by a non-pushState browser.
1497+ this.fragment = fragment;
1498+ var loc = this.location;
1499+ var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
1500+
1501+ // Transition from hashChange to pushState or vice versa if both are
1502+ // requested.
1503+ if (this._wantsHashChange && this._wantsPushState) {
1504+
1505+ // If we've started off with a route from a `pushState`-enabled
1506+ // browser, but we're currently in a browser that doesn't support it...
1507+ if (!this._hasPushState && !atRoot) {
1508+ this.fragment = this.getFragment(null, true);
1509+ this.location.replace(this.root + this.location.search + '#' + this.fragment);
1510+ // Return immediately as browser will do redirect to new url
1511+ return true;
1512+
1513+ // Or if we've started out with a hash-based route, but we're currently
1514+ // in a browser where it could be `pushState`-based instead...
1515+ } else if (this._hasPushState && atRoot && loc.hash) {
1516+ this.fragment = this.getHash().replace(routeStripper, '');
1517+ this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
1518+ }
1519+
1520+ }
1521+
1522+ if (!this.options.silent) return this.loadUrl();
1523+ },
1524+
1525+ // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
1526+ // but possibly useful for unit testing Routers.
1527+ stop: function() {
1528+ Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
1529+ clearInterval(this._checkUrlInterval);
1530+ History.started = false;
1531+ },
1532+
1533+ // Add a route to be tested when the fragment changes. Routes added later
1534+ // may override previous routes.
1535+ route: function(route, callback) {
1536+ this.handlers.unshift({route: route, callback: callback});
1537+ },
1538+
1539+ // Checks the current URL to see if it has changed, and if it has,
1540+ // calls `loadUrl`, normalizing across the hidden iframe.
1541+ checkUrl: function(e) {
1542+ var current = this.getFragment();
1543+ if (current === this.fragment && this.iframe) {
1544+ current = this.getFragment(this.getHash(this.iframe));
1545+ }
1546+ if (current === this.fragment) return false;
1547+ if (this.iframe) this.navigate(current);
1548+ this.loadUrl();
1549+ },
1550+
1551+ // Attempt to load the current URL fragment. If a route succeeds with a
1552+ // match, returns `true`. If no defined routes matches the fragment,
1553+ // returns `false`.
1554+ loadUrl: function(fragment) {
1555+ fragment = this.fragment = this.getFragment(fragment);
1556+ return _.any(this.handlers, function(handler) {
1557+ if (handler.route.test(fragment)) {
1558+ handler.callback(fragment);
1559+ return true;
1560+ }
1561+ });
1562+ },
1563+
1564+ // Save a fragment into the hash history, or replace the URL state if the
1565+ // 'replace' option is passed. You are responsible for properly URL-encoding
1566+ // the fragment in advance.
1567+ //
1568+ // The options object can contain `trigger: true` if you wish to have the
1569+ // route callback be fired (not usually desirable), or `replace: true`, if
1570+ // you wish to modify the current URL without adding an entry to the history.
1571+ navigate: function(fragment, options) {
1572+ if (!History.started) return false;
1573+ if (!options || options === true) options = {trigger: !!options};
1574+
1575+ var url = this.root + (fragment = this.getFragment(fragment || ''));
1576+
1577+ // Strip the fragment of the query and hash for matching.
1578+ fragment = fragment.replace(pathStripper, '');
1579+
1580+ if (this.fragment === fragment) return;
1581+ this.fragment = fragment;
1582+
1583+ // Don't include a trailing slash on the root.
1584+ if (fragment === '' && url !== '/') url = url.slice(0, -1);
1585+
1586+ // If pushState is available, we use it to set the fragment as a real URL.
1587+ if (this._hasPushState) {
1588+ this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
1589+
1590+ // If hash changes haven't been explicitly disabled, update the hash
1591+ // fragment to store history.
1592+ } else if (this._wantsHashChange) {
1593+ this._updateHash(this.location, fragment, options.replace);
1594+ if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
1595+ // Opening and closing the iframe tricks IE7 and earlier to push a
1596+ // history entry on hash-tag change. When replace is true, we don't
1597+ // want this.
1598+ if(!options.replace) this.iframe.document.open().close();
1599+ this._updateHash(this.iframe.location, fragment, options.replace);
1600+ }
1601+
1602+ // If you've told us that you explicitly don't want fallback hashchange-
1603+ // based history, then `navigate` becomes a page refresh.
1604+ } else {
1605+ return this.location.assign(url);
1606+ }
1607+ if (options.trigger) return this.loadUrl(fragment);
1608+ },
1609+
1610+ // Update the hash location, either replacing the current entry, or adding
1611+ // a new one to the browser history.
1612+ _updateHash: function(location, fragment, replace) {
1613+ if (replace) {
1614+ var href = location.href.replace(/(javascript:|#).*$/, '');
1615+ location.replace(href + '#' + fragment);
1616+ } else {
1617+ // Some browsers require that `hash` contains a leading #.
1618+ location.hash = '#' + fragment;
1619+ }
1620+ }
1621+
1622+ });
1623+
1624+ // Create the default Backbone.history.
1625+ Backbone.history = new History;
1626+
1627+ // Helpers
1628+ // -------
1629+
1630+ // Helper function to correctly set up the prototype chain, for subclasses.
1631+ // Similar to `goog.inherits`, but uses a hash of prototype properties and
1632+ // class properties to be extended.
1633+ var extend = function(protoProps, staticProps) {
1634+ var parent = this;
1635+ var child;
1636+
1637+ // The constructor function for the new subclass is either defined by you
1638+ // (the "constructor" property in your `extend` definition), or defaulted
1639+ // by us to simply call the parent's constructor.
1640+ if (protoProps && _.has(protoProps, 'constructor')) {
1641+ child = protoProps.constructor;
1642+ } else {
1643+ child = function(){ return parent.apply(this, arguments); };
1644+ }
1645+
1646+ // Add static properties to the constructor function, if supplied.
1647+ _.extend(child, parent, staticProps);
1648+
1649+ // Set the prototype chain to inherit from `parent`, without calling
1650+ // `parent`'s constructor function.
1651+ var Surrogate = function(){ this.constructor = child; };
1652+ Surrogate.prototype = parent.prototype;
1653+ child.prototype = new Surrogate;
1654+
1655+ // Add prototype properties (instance properties) to the subclass,
1656+ // if supplied.
1657+ if (protoProps) _.extend(child.prototype, protoProps);
1658+
1659+ // Set a convenience property in case the parent's prototype is needed
1660+ // later.
1661+ child.__super__ = parent.prototype;
1662+
1663+ return child;
1664+ };
1665+
1666+ // Set up inheritance for the model, collection, router, view and history.
1667+ Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
1668+
1669+ // Throw an error when a URL is needed, and none is supplied.
1670+ var urlError = function() {
1671+ throw new Error('A "url" property or function must be specified');
1672+ };
1673+
1674+ // Wrap an optional error callback with a fallback error event.
1675+ var wrapError = function(model, options) {
1676+ var error = options.error;
1677+ options.error = function(resp) {
1678+ if (error) error(model, resp, options);
1679+ model.trigger('error', model, resp, options);
1680+ };
1681+ };
1682+
1683+}).call(this);
1684\ No newline at end of file
1685
1686=== added directory 'web_unleashed/static/lib/jquery-addons'
1687=== added file 'web_unleashed/static/lib/jquery-addons/jquery.font_size.js'
1688--- web_unleashed/static/lib/jquery-addons/jquery.font_size.js 1970-01-01 00:00:00 +0000
1689+++ web_unleashed/static/lib/jquery-addons/jquery.font_size.js 2014-01-28 13:12:54 +0000
1690@@ -0,0 +1,11 @@
1691+(function(jQuery){
1692+
1693+ /*
1694+ * get the font size value
1695+ */
1696+ jQuery.fn.fontSize = function() {
1697+ return parseInt(this.css('fontSize').replace('px', ''));
1698+ };
1699+
1700+
1701+})($ || jQuery)
1702
1703=== added file 'web_unleashed/static/lib/jquery-addons/jquery.form_reset.js'
1704--- web_unleashed/static/lib/jquery-addons/jquery.form_reset.js 1970-01-01 00:00:00 +0000
1705+++ web_unleashed/static/lib/jquery-addons/jquery.form_reset.js 2014-01-28 13:12:54 +0000
1706@@ -0,0 +1,13 @@
1707+(function(jQuery){
1708+
1709+ /*
1710+ * reset from values.
1711+ */
1712+ jQuery.fn.reset = function() {
1713+ this.find('input,textarea,select').each(function(index, el){
1714+ $(el).val('');
1715+ });
1716+ };
1717+
1718+
1719+})($ || jQuery)
1720
1721=== added file 'web_unleashed/static/lib/jquery-addons/jquery.serialize_object.js'
1722--- web_unleashed/static/lib/jquery-addons/jquery.serialize_object.js 1970-01-01 00:00:00 +0000
1723+++ web_unleashed/static/lib/jquery-addons/jquery.serialize_object.js 2014-01-28 13:12:54 +0000
1724@@ -0,0 +1,17 @@
1725+(function(jQuery){
1726+
1727+ /*
1728+ * serialize a form into an Object.
1729+ */
1730+ $.fn.serializeObject = function(){
1731+ var data = this.serializeArray(),
1732+ obj = {}, i;
1733+
1734+ for(i=0 ; i < data.length ; i++){
1735+ obj[data[i]['name']] = $.isNumeric(data[i]['value']) ? parseInt(data[i]['value']) : data[i]['value'];
1736+ }
1737+
1738+ return obj;
1739+ };
1740+
1741+})($ || jQuery)
1742\ No newline at end of file
1743
1744=== added file 'web_unleashed/static/lib/jquery-addons/jquery.when_all.js'
1745--- web_unleashed/static/lib/jquery-addons/jquery.when_all.js 1970-01-01 00:00:00 +0000
1746+++ web_unleashed/static/lib/jquery-addons/jquery.when_all.js 2014-01-28 13:12:54 +0000
1747@@ -0,0 +1,56 @@
1748+(function(jQuery){
1749+
1750+ /*
1751+ * add a helper for $.Deferred, to keep waiting until all deferrer are executed before firing the global deferrer, keep info of each deferrer.
1752+ */
1753+ jQuery.whenAll = function( firstParam ) {
1754+ var args = $.makeArray(arguments),
1755+ i = 0,
1756+ length = args.length,
1757+ pValues = new Array( length ),
1758+ count = length,
1759+ pCount = length,
1760+ deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
1761+ firstParam :
1762+ jQuery.Deferred(),
1763+ promise = deferred.promise(),
1764+ state = 'resolved';
1765+
1766+ function alwaysFunc( i ) {
1767+ return function( value ) {
1768+ args[ i ] = arguments.length > 1 ? $.makeArray(arguments) : value;
1769+ state = this.state() === "rejected" ? "rejected" : state;
1770+ if ( !( --count ) ) {
1771+ var method = (state === "rejected"? "reject": "resolve") + "With";
1772+ deferred[method]( deferred, args );
1773+ }
1774+ };
1775+ }
1776+
1777+ function progressFunc( i ) {
1778+ return function( value ) {
1779+ pValues[ i ] = arguments.length > 1 ? $.makeArray(arguments) : value;
1780+ deferred.notifyWith( promise, pValues );
1781+ };
1782+ }
1783+
1784+ if ( length > 1 ) {
1785+ for ( ; i < length; i++ ) {
1786+ if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) {
1787+ args[ i ].promise().always( alwaysFunc(i))
1788+ .progress(progressFunc(i));
1789+ } else {
1790+ --count;
1791+ }
1792+ }
1793+ if ( !count ) {
1794+ deferred.resolveWith( deferred, args );
1795+ }
1796+ } else if ( deferred !== firstParam ) {
1797+ deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
1798+ }
1799+ return promise;
1800+ };
1801+
1802+
1803+})($ || jQuery)
1804
1805=== added directory 'web_unleashed/static/lib/marionette'
1806=== added file 'web_unleashed/static/lib/marionette/marionette.js'
1807--- web_unleashed/static/lib/marionette/marionette.js 1970-01-01 00:00:00 +0000
1808+++ web_unleashed/static/lib/marionette/marionette.js 2014-01-28 13:12:54 +0000
1809@@ -0,0 +1,2363 @@
1810+// MarionetteJS (Backbone.Marionette)
1811+// ----------------------------------
1812+// v1.1.0
1813+//
1814+// Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
1815+// Distributed under MIT license
1816+//
1817+// http://marionettejs.com
1818+
1819+
1820+
1821+/*!
1822+ * Includes BabySitter
1823+ * https://github.com/marionettejs/backbone.babysitter/
1824+ *
1825+ * Includes Wreqr
1826+ * https://github.com/marionettejs/backbone.wreqr/
1827+ */
1828+
1829+// Backbone.BabySitter
1830+// -------------------
1831+// v0.0.6
1832+//
1833+// Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
1834+// Distributed under MIT license
1835+//
1836+// http://github.com/babysitterjs/backbone.babysitter
1837+
1838+// Backbone.ChildViewContainer
1839+// ---------------------------
1840+//
1841+// Provide a container to store, retrieve and
1842+// shut down child views.
1843+
1844+Backbone.ChildViewContainer = (function(Backbone, _){
1845+
1846+ // Container Constructor
1847+ // ---------------------
1848+
1849+ var Container = function(views){
1850+ this._views = {};
1851+ this._indexByModel = {};
1852+ this._indexByCustom = {};
1853+ this._updateLength();
1854+
1855+ _.each(views, this.add, this);
1856+ };
1857+
1858+ // Container Methods
1859+ // -----------------
1860+
1861+ _.extend(Container.prototype, {
1862+
1863+ // Add a view to this container. Stores the view
1864+ // by `cid` and makes it searchable by the model
1865+ // cid (and model itself). Optionally specify
1866+ // a custom key to store an retrieve the view.
1867+ add: function(view, customIndex){
1868+ var viewCid = view.cid;
1869+
1870+ // store the view
1871+ this._views[viewCid] = view;
1872+
1873+ // index it by model
1874+ if (view.model){
1875+ this._indexByModel[view.model.cid] = viewCid;
1876+ }
1877+
1878+ // index by custom
1879+ if (customIndex){
1880+ this._indexByCustom[customIndex] = viewCid;
1881+ }
1882+
1883+ this._updateLength();
1884+ },
1885+
1886+ // Find a view by the model that was attached to
1887+ // it. Uses the model's `cid` to find it.
1888+ findByModel: function(model){
1889+ return this.findByModelCid(model.cid);
1890+ },
1891+
1892+ // Find a view by the `cid` of the model that was attached to
1893+ // it. Uses the model's `cid` to find the view `cid` and
1894+ // retrieve the view using it.
1895+ findByModelCid: function(modelCid){
1896+ var viewCid = this._indexByModel[modelCid];
1897+ return this.findByCid(viewCid);
1898+ },
1899+
1900+ // Find a view by a custom indexer.
1901+ findByCustom: function(index){
1902+ var viewCid = this._indexByCustom[index];
1903+ return this.findByCid(viewCid);
1904+ },
1905+
1906+ // Find by index. This is not guaranteed to be a
1907+ // stable index.
1908+ findByIndex: function(index){
1909+ return _.values(this._views)[index];
1910+ },
1911+
1912+ // retrieve a view by it's `cid` directly
1913+ findByCid: function(cid){
1914+ return this._views[cid];
1915+ },
1916+
1917+ // Remove a view
1918+ remove: function(view){
1919+ var viewCid = view.cid;
1920+
1921+ // delete model index
1922+ if (view.model){
1923+ delete this._indexByModel[view.model.cid];
1924+ }
1925+
1926+ // delete custom index
1927+ _.any(this._indexByCustom, function(cid, key) {
1928+ if (cid === viewCid) {
1929+ delete this._indexByCustom[key];
1930+ return true;
1931+ }
1932+ }, this);
1933+
1934+ // remove the view from the container
1935+ delete this._views[viewCid];
1936+
1937+ // update the length
1938+ this._updateLength();
1939+ },
1940+
1941+ // Call a method on every view in the container,
1942+ // passing parameters to the call method one at a
1943+ // time, like `function.call`.
1944+ call: function(method){
1945+ this.apply(method, _.tail(arguments));
1946+ },
1947+
1948+ // Apply a method on every view in the container,
1949+ // passing parameters to the call method one at a
1950+ // time, like `function.apply`.
1951+ apply: function(method, args){
1952+ _.each(this._views, function(view){
1953+ if (_.isFunction(view[method])){
1954+ view[method].apply(view, args || []);
1955+ }
1956+ });
1957+ },
1958+
1959+ // Update the `.length` attribute on this container
1960+ _updateLength: function(){
1961+ this.length = _.size(this._views);
1962+ }
1963+ });
1964+
1965+ // Borrowing this code from Backbone.Collection:
1966+ // http://backbonejs.org/docs/backbone.html#section-106
1967+ //
1968+ // Mix in methods from Underscore, for iteration, and other
1969+ // collection related features.
1970+ var methods = ['forEach', 'each', 'map', 'find', 'detect', 'filter',
1971+ 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
1972+ 'contains', 'invoke', 'toArray', 'first', 'initial', 'rest',
1973+ 'last', 'without', 'isEmpty', 'pluck'];
1974+
1975+ _.each(methods, function(method) {
1976+ Container.prototype[method] = function() {
1977+ var views = _.values(this._views);
1978+ var args = [views].concat(_.toArray(arguments));
1979+ return _[method].apply(_, args);
1980+ };
1981+ });
1982+
1983+ // return the public API
1984+ return Container;
1985+})(Backbone, _);
1986+
1987+// Backbone.Wreqr (Backbone.Marionette)
1988+// ----------------------------------
1989+// v0.2.0
1990+//
1991+// Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
1992+// Distributed under MIT license
1993+//
1994+// http://github.com/marionettejs/backbone.wreqr
1995+
1996+
1997+Backbone.Wreqr = (function(Backbone, Marionette, _){
1998+ "use strict";
1999+ var Wreqr = {};
2000+
2001+ // Handlers
2002+// --------
2003+// A registry of functions to call, given a name
2004+
2005+Wreqr.Handlers = (function(Backbone, _){
2006+ "use strict";
2007+
2008+ // Constructor
2009+ // -----------
2010+
2011+ var Handlers = function(options){
2012+ this.options = options;
2013+ this._wreqrHandlers = {};
2014+
2015+ if (_.isFunction(this.initialize)){
2016+ this.initialize(options);
2017+ }
2018+ };
2019+
2020+ Handlers.extend = Backbone.Model.extend;
2021+
2022+ // Instance Members
2023+ // ----------------
2024+
2025+ _.extend(Handlers.prototype, Backbone.Events, {
2026+
2027+ // Add multiple handlers using an object literal configuration
2028+ setHandlers: function(handlers){
2029+ _.each(handlers, function(handler, name){
2030+ var context = null;
2031+
2032+ if (_.isObject(handler) && !_.isFunction(handler)){
2033+ context = handler.context;
2034+ handler = handler.callback;
2035+ }
2036+
2037+ this.setHandler(name, handler, context);
2038+ }, this);
2039+ },
2040+
2041+ // Add a handler for the given name, with an
2042+ // optional context to run the handler within
2043+ setHandler: function(name, handler, context){
2044+ var config = {
2045+ callback: handler,
2046+ context: context
2047+ };
2048+
2049+ this._wreqrHandlers[name] = config;
2050+
2051+ this.trigger("handler:add", name, handler, context);
2052+ },
2053+
2054+ // Determine whether or not a handler is registered
2055+ hasHandler: function(name){
2056+ return !! this._wreqrHandlers[name];
2057+ },
2058+
2059+ // Get the currently registered handler for
2060+ // the specified name. Throws an exception if
2061+ // no handler is found.
2062+ getHandler: function(name){
2063+ var config = this._wreqrHandlers[name];
2064+
2065+ if (!config){
2066+ throw new Error("Handler not found for '" + name + "'");
2067+ }
2068+
2069+ return function(){
2070+ var args = Array.prototype.slice.apply(arguments);
2071+ return config.callback.apply(config.context, args);
2072+ };
2073+ },
2074+
2075+ // Remove a handler for the specified name
2076+ removeHandler: function(name){
2077+ delete this._wreqrHandlers[name];
2078+ },
2079+
2080+ // Remove all handlers from this registry
2081+ removeAllHandlers: function(){
2082+ this._wreqrHandlers = {};
2083+ }
2084+ });
2085+
2086+ return Handlers;
2087+})(Backbone, _);
2088+
2089+ // Wreqr.CommandStorage
2090+// --------------------
2091+//
2092+// Store and retrieve commands for execution.
2093+Wreqr.CommandStorage = (function(){
2094+ "use strict";
2095+
2096+ // Constructor function
2097+ var CommandStorage = function(options){
2098+ this.options = options;
2099+ this._commands = {};
2100+
2101+ if (_.isFunction(this.initialize)){
2102+ this.initialize(options);
2103+ }
2104+ };
2105+
2106+ // Instance methods
2107+ _.extend(CommandStorage.prototype, Backbone.Events, {
2108+
2109+ // Get an object literal by command name, that contains
2110+ // the `commandName` and the `instances` of all commands
2111+ // represented as an array of arguments to process
2112+ getCommands: function(commandName){
2113+ var commands = this._commands[commandName];
2114+
2115+ // we don't have it, so add it
2116+ if (!commands){
2117+
2118+ // build the configuration
2119+ commands = {
2120+ command: commandName,
2121+ instances: []
2122+ };
2123+
2124+ // store it
2125+ this._commands[commandName] = commands;
2126+ }
2127+
2128+ return commands;
2129+ },
2130+
2131+ // Add a command by name, to the storage and store the
2132+ // args for the command
2133+ addCommand: function(commandName, args){
2134+ var command = this.getCommands(commandName);
2135+ command.instances.push(args);
2136+ },
2137+
2138+ // Clear all commands for the given `commandName`
2139+ clearCommands: function(commandName){
2140+ var command = this.getCommands(commandName);
2141+ command.instances = [];
2142+ }
2143+ });
2144+
2145+ return CommandStorage;
2146+})();
2147+
2148+ // Wreqr.Commands
2149+// --------------
2150+//
2151+// A simple command pattern implementation. Register a command
2152+// handler and execute it.
2153+Wreqr.Commands = (function(Wreqr){
2154+ "use strict";
2155+
2156+ return Wreqr.Handlers.extend({
2157+ // default storage type
2158+ storageType: Wreqr.CommandStorage,
2159+
2160+ constructor: function(options){
2161+ this.options = options || {};
2162+
2163+ this._initializeStorage(this.options);
2164+ this.on("handler:add", this._executeCommands, this);
2165+
2166+ var args = Array.prototype.slice.call(arguments);
2167+ Wreqr.Handlers.prototype.constructor.apply(this, args);
2168+ },
2169+
2170+ // Execute a named command with the supplied args
2171+ execute: function(name, args){
2172+ name = arguments[0];
2173+ args = Array.prototype.slice.call(arguments, 1);
2174+
2175+ if (this.hasHandler(name)){
2176+ this.getHandler(name).apply(this, args);
2177+ } else {
2178+ this.storage.addCommand(name, args);
2179+ }
2180+
2181+ },
2182+
2183+ // Internal method to handle bulk execution of stored commands
2184+ _executeCommands: function(name, handler, context){
2185+ var command = this.storage.getCommands(name);
2186+
2187+ // loop through and execute all the stored command instances
2188+ _.each(command.instances, function(args){
2189+ handler.apply(context, args);
2190+ });
2191+
2192+ this.storage.clearCommands(name);
2193+ },
2194+
2195+ // Internal method to initialize storage either from the type's
2196+ // `storageType` or the instance `options.storageType`.
2197+ _initializeStorage: function(options){
2198+ var storage;
2199+
2200+ var StorageType = options.storageType || this.storageType;
2201+ if (_.isFunction(StorageType)){
2202+ storage = new StorageType();
2203+ } else {
2204+ storage = StorageType;
2205+ }
2206+
2207+ this.storage = storage;
2208+ }
2209+ });
2210+
2211+})(Wreqr);
2212+
2213+ // Wreqr.RequestResponse
2214+// ---------------------
2215+//
2216+// A simple request/response implementation. Register a
2217+// request handler, and return a response from it
2218+Wreqr.RequestResponse = (function(Wreqr){
2219+ "use strict";
2220+
2221+ return Wreqr.Handlers.extend({
2222+ request: function(){
2223+ var name = arguments[0];
2224+ var args = Array.prototype.slice.call(arguments, 1);
2225+
2226+ return this.getHandler(name).apply(this, args);
2227+ }
2228+ });
2229+
2230+})(Wreqr);
2231+
2232+ // Event Aggregator
2233+// ----------------
2234+// A pub-sub object that can be used to decouple various parts
2235+// of an application through event-driven architecture.
2236+
2237+Wreqr.EventAggregator = (function(Backbone, _){
2238+ "use strict";
2239+ var EA = function(){};
2240+
2241+ // Copy the `extend` function used by Backbone's classes
2242+ EA.extend = Backbone.Model.extend;
2243+
2244+ // Copy the basic Backbone.Events on to the event aggregator
2245+ _.extend(EA.prototype, Backbone.Events);
2246+
2247+ return EA;
2248+})(Backbone, _);
2249+
2250+
2251+ return Wreqr;
2252+})(Backbone, Backbone.Marionette, _);
2253+
2254+var Marionette = (function(global, Backbone, _){
2255+ "use strict";
2256+
2257+ // Define and export the Marionette namespace
2258+ var Marionette = {};
2259+ Backbone.Marionette = Marionette;
2260+
2261+ // Get the DOM manipulator for later use
2262+ Marionette.$ = Backbone.$;
2263+
2264+// Helpers
2265+// -------
2266+
2267+// For slicing `arguments` in functions
2268+var protoSlice = Array.prototype.slice;
2269+function slice(args) {
2270+ return protoSlice.call(args);
2271+}
2272+
2273+function throwError(message, name) {
2274+ var error = new Error(message);
2275+ error.name = name || 'Error';
2276+ throw error;
2277+}
2278+
2279+// Marionette.extend
2280+// -----------------
2281+
2282+// Borrow the Backbone `extend` method so we can use it as needed
2283+Marionette.extend = Backbone.Model.extend;
2284+
2285+// Marionette.getOption
2286+// --------------------
2287+
2288+// Retrieve an object, function or other value from a target
2289+// object or its `options`, with `options` taking precedence.
2290+Marionette.getOption = function(target, optionName){
2291+ if (!target || !optionName){ return; }
2292+ var value;
2293+
2294+ if (target.options && (optionName in target.options) && (target.options[optionName] !== undefined)){
2295+ value = target.options[optionName];
2296+ } else {
2297+ value = target[optionName];
2298+ }
2299+
2300+ return value;
2301+};
2302+
2303+// Trigger an event and/or a corresponding method name. Examples:
2304+//
2305+// `this.triggerMethod("foo")` will trigger the "foo" event and
2306+// call the "onFoo" method.
2307+//
2308+// `this.triggerMethod("foo:bar") will trigger the "foo:bar" event and
2309+// call the "onFooBar" method.
2310+Marionette.triggerMethod = (function(){
2311+
2312+ // split the event name on the :
2313+ var splitter = /(^|:)(\w)/gi;
2314+
2315+ // take the event section ("section1:section2:section3")
2316+ // and turn it in to uppercase name
2317+ function getEventName(match, prefix, eventName) {
2318+ return eventName.toUpperCase();
2319+ }
2320+
2321+ // actual triggerMethod name
2322+ var triggerMethod = function(event) {
2323+ // get the method name from the event name
2324+ var methodName = 'on' + event.replace(splitter, getEventName);
2325+ var method = this[methodName];
2326+
2327+ // trigger the event, if a trigger method exists
2328+ if(_.isFunction(this.trigger)) {
2329+ this.trigger.apply(this, arguments);
2330+ }
2331+
2332+ // call the onMethodName if it exists
2333+ if (_.isFunction(method)) {
2334+ // pass all arguments, except the event name
2335+ return method.apply(this, _.tail(arguments));
2336+ }
2337+ };
2338+
2339+ return triggerMethod;
2340+})();
2341+
2342+// DOMRefresh
2343+// ----------
2344+//
2345+// Monitor a view's state, and after it has been rendered and shown
2346+// in the DOM, trigger a "dom:refresh" event every time it is
2347+// re-rendered.
2348+
2349+Marionette.MonitorDOMRefresh = (function(){
2350+ // track when the view has been shown in the DOM,
2351+ // using a Marionette.Region (or by other means of triggering "show")
2352+ function handleShow(view){
2353+ view._isShown = true;
2354+ triggerDOMRefresh(view);
2355+ }
2356+
2357+ // track when the view has been rendered
2358+ function handleRender(view){
2359+ view._isRendered = true;
2360+ triggerDOMRefresh(view);
2361+ }
2362+
2363+ // Trigger the "dom:refresh" event and corresponding "onDomRefresh" method
2364+ function triggerDOMRefresh(view){
2365+ if (view._isShown && view._isRendered){
2366+ if (_.isFunction(view.triggerMethod)){
2367+ view.triggerMethod("dom:refresh");
2368+ }
2369+ }
2370+ }
2371+
2372+ // Export public API
2373+ return function(view){
2374+ view.listenTo(view, "show", function(){
2375+ handleShow(view);
2376+ });
2377+
2378+ view.listenTo(view, "render", function(){
2379+ handleRender(view);
2380+ });
2381+ };
2382+})();
2383+
2384+
2385+// Marionette.bindEntityEvents & unbindEntityEvents
2386+// ---------------------------
2387+//
2388+// These methods are used to bind/unbind a backbone "entity" (collection/model)
2389+// to methods on a target object.
2390+//
2391+// The first parameter, `target`, must have a `listenTo` method from the
2392+// EventBinder object.
2393+//
2394+// The second parameter is the entity (Backbone.Model or Backbone.Collection)
2395+// to bind the events from.
2396+//
2397+// The third parameter is a hash of { "event:name": "eventHandler" }
2398+// configuration. Multiple handlers can be separated by a space. A
2399+// function can be supplied instead of a string handler name.
2400+
2401+(function(Marionette){
2402+ "use strict";
2403+
2404+ // Bind the event to handlers specified as a string of
2405+ // handler names on the target object
2406+ function bindFromStrings(target, entity, evt, methods){
2407+ var methodNames = methods.split(/\s+/);
2408+
2409+ _.each(methodNames,function(methodName) {
2410+
2411+ var method = target[methodName];
2412+ if(!method) {
2413+ throwError("Method '"+ methodName +"' was configured as an event handler, but does not exist.");
2414+ }
2415+
2416+ target.listenTo(entity, evt, method, target);
2417+ });
2418+ }
2419+
2420+ // Bind the event to a supplied callback function
2421+ function bindToFunction(target, entity, evt, method){
2422+ target.listenTo(entity, evt, method, target);
2423+ }
2424+
2425+ // Bind the event to handlers specified as a string of
2426+ // handler names on the target object
2427+ function unbindFromStrings(target, entity, evt, methods){
2428+ var methodNames = methods.split(/\s+/);
2429+
2430+ _.each(methodNames,function(methodName) {
2431+ var method = target[methodName];
2432+ target.stopListening(entity, evt, method, target);
2433+ });
2434+ }
2435+
2436+ // Bind the event to a supplied callback function
2437+ function unbindToFunction(target, entity, evt, method){
2438+ target.stopListening(entity, evt, method, target);
2439+ }
2440+
2441+
2442+ // generic looping function
2443+ function iterateEvents(target, entity, bindings, functionCallback, stringCallback){
2444+ if (!entity || !bindings) { return; }
2445+
2446+ // allow the bindings to be a function
2447+ if (_.isFunction(bindings)){
2448+ bindings = bindings.call(target);
2449+ }
2450+
2451+ // iterate the bindings and bind them
2452+ _.each(bindings, function(methods, evt){
2453+
2454+ // allow for a function as the handler,
2455+ // or a list of event names as a string
2456+ if (_.isFunction(methods)){
2457+ functionCallback(target, entity, evt, methods);
2458+ } else {
2459+ stringCallback(target, entity, evt, methods);
2460+ }
2461+
2462+ });
2463+ }
2464+
2465+ // Export Public API
2466+ Marionette.bindEntityEvents = function(target, entity, bindings){
2467+ iterateEvents(target, entity, bindings, bindToFunction, bindFromStrings);
2468+ };
2469+
2470+ Marionette.unbindEntityEvents = function(target, entity, bindings){
2471+ iterateEvents(target, entity, bindings, unbindToFunction, unbindFromStrings);
2472+ };
2473+
2474+})(Marionette);
2475+
2476+
2477+// Callbacks
2478+// ---------
2479+
2480+// A simple way of managing a collection of callbacks
2481+// and executing them at a later point in time, using jQuery's
2482+// `Deferred` object.
2483+Marionette.Callbacks = function(){
2484+ this._deferred = Marionette.$.Deferred();
2485+ this._callbacks = [];
2486+};
2487+
2488+_.extend(Marionette.Callbacks.prototype, {
2489+
2490+ // Add a callback to be executed. Callbacks added here are
2491+ // guaranteed to execute, even if they are added after the
2492+ // `run` method is called.
2493+ add: function(callback, contextOverride){
2494+ this._callbacks.push({cb: callback, ctx: contextOverride});
2495+
2496+ this._deferred.done(function(context, options){
2497+ if (contextOverride){ context = contextOverride; }
2498+ callback.call(context, options);
2499+ });
2500+ },
2501+
2502+ // Run all registered callbacks with the context specified.
2503+ // Additional callbacks can be added after this has been run
2504+ // and they will still be executed.
2505+ run: function(options, context){
2506+ this._deferred.resolve(context, options);
2507+ },
2508+
2509+ // Resets the list of callbacks to be run, allowing the same list
2510+ // to be run multiple times - whenever the `run` method is called.
2511+ reset: function(){
2512+ var callbacks = this._callbacks;
2513+ this._deferred = Marionette.$.Deferred();
2514+ this._callbacks = [];
2515+
2516+ _.each(callbacks, function(cb){
2517+ this.add(cb.cb, cb.ctx);
2518+ }, this);
2519+ }
2520+});
2521+
2522+
2523+// Marionette Controller
2524+// ---------------------
2525+//
2526+// A multi-purpose object to use as a controller for
2527+// modules and routers, and as a mediator for workflow
2528+// and coordination of other objects, views, and more.
2529+Marionette.Controller = function(options){
2530+ this.triggerMethod = Marionette.triggerMethod;
2531+ this.options = options || {};
2532+
2533+ if (_.isFunction(this.initialize)){
2534+ this.initialize(this.options);
2535+ }
2536+};
2537+
2538+Marionette.Controller.extend = Marionette.extend;
2539+
2540+// Controller Methods
2541+// --------------
2542+
2543+// Ensure it can trigger events with Backbone.Events
2544+_.extend(Marionette.Controller.prototype, Backbone.Events, {
2545+ close: function(){
2546+ this.stopListening();
2547+ this.triggerMethod("close");
2548+ this.unbind();
2549+ }
2550+});
2551+
2552+// Region
2553+// ------
2554+//
2555+// Manage the visual regions of your composite application. See
2556+// http://lostechies.com/derickbailey/2011/12/12/composite-js-apps-regions-and-region-managers/
2557+
2558+Marionette.Region = function(options){
2559+ this.options = options || {};
2560+
2561+ this.el = Marionette.getOption(this, "el");
2562+
2563+ if (!this.el){
2564+ var err = new Error("An 'el' must be specified for a region.");
2565+ err.name = "NoElError";
2566+ throw err;
2567+ }
2568+
2569+ if (this.initialize){
2570+ var args = Array.prototype.slice.apply(arguments);
2571+ this.initialize.apply(this, args);
2572+ }
2573+};
2574+
2575+
2576+// Region Type methods
2577+// -------------------
2578+
2579+_.extend(Marionette.Region, {
2580+
2581+ // Build an instance of a region by passing in a configuration object
2582+ // and a default region type to use if none is specified in the config.
2583+ //
2584+ // The config object should either be a string as a jQuery DOM selector,
2585+ // a Region type directly, or an object literal that specifies both
2586+ // a selector and regionType:
2587+ //
2588+ // ```js
2589+ // {
2590+ // selector: "#foo",
2591+ // regionType: MyCustomRegion
2592+ // }
2593+ // ```
2594+ //
2595+ buildRegion: function(regionConfig, defaultRegionType){
2596+
2597+ var regionIsString = (typeof regionConfig === "string");
2598+ var regionSelectorIsString = (typeof regionConfig.selector === "string");
2599+ var regionTypeIsUndefined = (typeof regionConfig.regionType === "undefined");
2600+ var regionIsType = (typeof regionConfig === "function");
2601+
2602+ if (!regionIsType && !regionIsString && !regionSelectorIsString) {
2603+ throw new Error("Region must be specified as a Region type, a selector string or an object with selector property");
2604+ }
2605+
2606+ var selector, RegionType;
2607+
2608+ // get the selector for the region
2609+
2610+ if (regionIsString) {
2611+ selector = regionConfig;
2612+ }
2613+
2614+ if (regionConfig.selector) {
2615+ selector = regionConfig.selector;
2616+ }
2617+
2618+ // get the type for the region
2619+
2620+ if (regionIsType){
2621+ RegionType = regionConfig;
2622+ }
2623+
2624+ if (!regionIsType && regionTypeIsUndefined) {
2625+ RegionType = defaultRegionType;
2626+ }
2627+
2628+ if (regionConfig.regionType) {
2629+ RegionType = regionConfig.regionType;
2630+ }
2631+
2632+ // build the region instance
2633+ var region = new RegionType({
2634+ el: selector
2635+ });
2636+
2637+ // override the `getEl` function if we have a parentEl
2638+ // this must be overridden to ensure the selector is found
2639+ // on the first use of the region. if we try to assign the
2640+ // region's `el` to `parentEl.find(selector)` in the object
2641+ // literal to build the region, the element will not be
2642+ // guaranteed to be in the DOM already, and will cause problems
2643+ if (regionConfig.parentEl){
2644+
2645+ region.getEl = function(selector) {
2646+ var parentEl = regionConfig.parentEl;
2647+ if (_.isFunction(parentEl)){
2648+ parentEl = parentEl();
2649+ }
2650+ return parentEl.find(selector);
2651+ };
2652+ }
2653+
2654+ return region;
2655+ }
2656+
2657+});
2658+
2659+// Region Instance Methods
2660+// -----------------------
2661+
2662+_.extend(Marionette.Region.prototype, Backbone.Events, {
2663+
2664+ // Displays a backbone view instance inside of the region.
2665+ // Handles calling the `render` method for you. Reads content
2666+ // directly from the `el` attribute. Also calls an optional
2667+ // `onShow` and `close` method on your view, just after showing
2668+ // or just before closing the view, respectively.
2669+ show: function(view){
2670+
2671+ this.ensureEl();
2672+
2673+ var isViewClosed = view.isClosed || _.isUndefined(view.$el);
2674+
2675+ var isDifferentView = view !== this.currentView;
2676+
2677+ if (isDifferentView) {
2678+ this.close();
2679+ }
2680+
2681+ view.render();
2682+
2683+ if (isDifferentView || isViewClosed) {
2684+ this.open(view);
2685+ }
2686+
2687+ this.currentView = view;
2688+
2689+ Marionette.triggerMethod.call(this, "show", view);
2690+ Marionette.triggerMethod.call(view, "show");
2691+ },
2692+
2693+ ensureEl: function(){
2694+ if (!this.$el || this.$el.length === 0){
2695+ this.$el = this.getEl(this.el);
2696+ }
2697+ },
2698+
2699+ // Override this method to change how the region finds the
2700+ // DOM element that it manages. Return a jQuery selector object.
2701+ getEl: function(selector){
2702+ return Marionette.$(selector);
2703+ },
2704+
2705+ // Override this method to change how the new view is
2706+ // appended to the `$el` that the region is managing
2707+ open: function(view){
2708+ this.$el.empty().append(view.el);
2709+ },
2710+
2711+ // Close the current view, if there is one. If there is no
2712+ // current view, it does nothing and returns immediately.
2713+ close: function(){
2714+ var view = this.currentView;
2715+ if (!view || view.isClosed){ return; }
2716+
2717+ // call 'close' or 'remove', depending on which is found
2718+ if (view.close) { view.close(); }
2719+ else if (view.remove) { view.remove(); }
2720+
2721+ Marionette.triggerMethod.call(this, "close");
2722+
2723+ delete this.currentView;
2724+ },
2725+
2726+ // Attach an existing view to the region. This
2727+ // will not call `render` or `onShow` for the new view,
2728+ // and will not replace the current HTML for the `el`
2729+ // of the region.
2730+ attachView: function(view){
2731+ this.currentView = view;
2732+ },
2733+
2734+ // Reset the region by closing any existing view and
2735+ // clearing out the cached `$el`. The next time a view
2736+ // is shown via this region, the region will re-query the
2737+ // DOM for the region's `el`.
2738+ reset: function(){
2739+ this.close();
2740+ delete this.$el;
2741+ }
2742+});
2743+
2744+// Copy the `extend` function used by Backbone's classes
2745+Marionette.Region.extend = Marionette.extend;
2746+
2747+// Marionette.RegionManager
2748+// ------------------------
2749+//
2750+// Manage one or more related `Marionette.Region` objects.
2751+Marionette.RegionManager = (function(Marionette){
2752+
2753+ var RegionManager = Marionette.Controller.extend({
2754+ constructor: function(options){
2755+ this._regions = {};
2756+ Marionette.Controller.prototype.constructor.call(this, options);
2757+ },
2758+
2759+ // Add multiple regions using an object literal, where
2760+ // each key becomes the region name, and each value is
2761+ // the region definition.
2762+ addRegions: function(regionDefinitions, defaults){
2763+ var regions = {};
2764+
2765+ _.each(regionDefinitions, function(definition, name){
2766+ if (typeof definition === "string"){
2767+ definition = { selector: definition };
2768+ }
2769+
2770+ if (definition.selector){
2771+ definition = _.defaults({}, definition, defaults);
2772+ }
2773+
2774+ var region = this.addRegion(name, definition);
2775+ regions[name] = region;
2776+ }, this);
2777+
2778+ return regions;
2779+ },
2780+
2781+ // Add an individual region to the region manager,
2782+ // and return the region instance
2783+ addRegion: function(name, definition){
2784+ var region;
2785+
2786+ var isObject = _.isObject(definition);
2787+ var isString = _.isString(definition);
2788+ var hasSelector = !!definition.selector;
2789+
2790+ if (isString || (isObject && hasSelector)){
2791+ region = Marionette.Region.buildRegion(definition, Marionette.Region);
2792+ } else if (_.isFunction(definition)){
2793+ region = Marionette.Region.buildRegion(definition, Marionette.Region);
2794+ } else {
2795+ region = definition;
2796+ }
2797+
2798+ this._store(name, region);
2799+ this.triggerMethod("region:add", name, region);
2800+ return region;
2801+ },
2802+
2803+ // Get a region by name
2804+ get: function(name){
2805+ return this._regions[name];
2806+ },
2807+
2808+ // Remove a region by name
2809+ removeRegion: function(name){
2810+ var region = this._regions[name];
2811+ this._remove(name, region);
2812+ },
2813+
2814+ // Close all regions in the region manager, and
2815+ // remove them
2816+ removeRegions: function(){
2817+ _.each(this._regions, function(region, name){
2818+ this._remove(name, region);
2819+ }, this);
2820+ },
2821+
2822+ // Close all regions in the region manager, but
2823+ // leave them attached
2824+ closeRegions: function(){
2825+ _.each(this._regions, function(region, name){
2826+ region.close();
2827+ }, this);
2828+ },
2829+
2830+ // Close all regions and shut down the region
2831+ // manager entirely
2832+ close: function(){
2833+ this.removeRegions();
2834+ var args = Array.prototype.slice.call(arguments);
2835+ Marionette.Controller.prototype.close.apply(this, args);
2836+ },
2837+
2838+ // internal method to store regions
2839+ _store: function(name, region){
2840+ this._regions[name] = region;
2841+ this._setLength();
2842+ },
2843+
2844+ // internal method to remove a region
2845+ _remove: function(name, region){
2846+ region.close();
2847+ delete this._regions[name];
2848+ this._setLength();
2849+ this.triggerMethod("region:remove", name, region);
2850+ },
2851+
2852+ // set the number of regions current held
2853+ _setLength: function(){
2854+ this.length = _.size(this._regions);
2855+ }
2856+
2857+ });
2858+
2859+ // Borrowing this code from Backbone.Collection:
2860+ // http://backbonejs.org/docs/backbone.html#section-106
2861+ //
2862+ // Mix in methods from Underscore, for iteration, and other
2863+ // collection related features.
2864+ var methods = ['forEach', 'each', 'map', 'find', 'detect', 'filter',
2865+ 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
2866+ 'contains', 'invoke', 'toArray', 'first', 'initial', 'rest',
2867+ 'last', 'without', 'isEmpty', 'pluck'];
2868+
2869+ _.each(methods, function(method) {
2870+ RegionManager.prototype[method] = function() {
2871+ var regions = _.values(this._regions);
2872+ var args = [regions].concat(_.toArray(arguments));
2873+ return _[method].apply(_, args);
2874+ };
2875+ });
2876+
2877+ return RegionManager;
2878+})(Marionette);
2879+
2880+
2881+// Template Cache
2882+// --------------
2883+
2884+// Manage templates stored in `<script>` blocks,
2885+// caching them for faster access.
2886+Marionette.TemplateCache = function(templateId){
2887+ this.templateId = templateId;
2888+};
2889+
2890+// TemplateCache object-level methods. Manage the template
2891+// caches from these method calls instead of creating
2892+// your own TemplateCache instances
2893+_.extend(Marionette.TemplateCache, {
2894+ templateCaches: {},
2895+
2896+ // Get the specified template by id. Either
2897+ // retrieves the cached version, or loads it
2898+ // from the DOM.
2899+ get: function(templateId){
2900+ var cachedTemplate = this.templateCaches[templateId];
2901+
2902+ if (!cachedTemplate){
2903+ cachedTemplate = new Marionette.TemplateCache(templateId);
2904+ this.templateCaches[templateId] = cachedTemplate;
2905+ }
2906+
2907+ return cachedTemplate.load();
2908+ },
2909+
2910+ // Clear templates from the cache. If no arguments
2911+ // are specified, clears all templates:
2912+ // `clear()`
2913+ //
2914+ // If arguments are specified, clears each of the
2915+ // specified templates from the cache:
2916+ // `clear("#t1", "#t2", "...")`
2917+ clear: function(){
2918+ var i;
2919+ var args = slice(arguments);
2920+ var length = args.length;
2921+
2922+ if (length > 0){
2923+ for(i=0; i<length; i++){
2924+ delete this.templateCaches[args[i]];
2925+ }
2926+ } else {
2927+ this.templateCaches = {};
2928+ }
2929+ }
2930+});
2931+
2932+// TemplateCache instance methods, allowing each
2933+// template cache object to manage its own state
2934+// and know whether or not it has been loaded
2935+_.extend(Marionette.TemplateCache.prototype, {
2936+
2937+ // Internal method to load the template
2938+ load: function(){
2939+ // Guard clause to prevent loading this template more than once
2940+ if (this.compiledTemplate){
2941+ return this.compiledTemplate;
2942+ }
2943+
2944+ // Load the template and compile it
2945+ var template = this.loadTemplate(this.templateId);
2946+ this.compiledTemplate = this.compileTemplate(template);
2947+
2948+ return this.compiledTemplate;
2949+ },
2950+
2951+ // Load a template from the DOM, by default. Override
2952+ // this method to provide your own template retrieval
2953+ // For asynchronous loading with AMD/RequireJS, consider
2954+ // using a template-loader plugin as described here:
2955+ // https://github.com/marionettejs/backbone.marionette/wiki/Using-marionette-with-requirejs
2956+ loadTemplate: function(templateId){
2957+ var template = Marionette.$(templateId).html();
2958+
2959+ if (!template || template.length === 0){
2960+ throwError("Could not find template: '" + templateId + "'", "NoTemplateError");
2961+ }
2962+
2963+ return template;
2964+ },
2965+
2966+ // Pre-compile the template before caching it. Override
2967+ // this method if you do not need to pre-compile a template
2968+ // (JST / RequireJS for example) or if you want to change
2969+ // the template engine used (Handebars, etc).
2970+ compileTemplate: function(rawTemplate){
2971+ return _.template(rawTemplate);
2972+ }
2973+});
2974+
2975+
2976+// Renderer
2977+// --------
2978+
2979+// Render a template with data by passing in the template
2980+// selector and the data to render.
2981+Marionette.Renderer = {
2982+
2983+ // Render a template with data. The `template` parameter is
2984+ // passed to the `TemplateCache` object to retrieve the
2985+ // template function. Override this method to provide your own
2986+ // custom rendering and template handling for all of Marionette.
2987+ render: function(template, data){
2988+
2989+ if (!template) {
2990+ var error = new Error("Cannot render the template since it's false, null or undefined.");
2991+ error.name = "TemplateNotFoundError";
2992+ throw error;
2993+ }
2994+
2995+ var templateFunc;
2996+ if (typeof template === "function"){
2997+ templateFunc = template;
2998+ } else {
2999+ templateFunc = Marionette.TemplateCache.get(template);
3000+ }
3001+
3002+ return templateFunc(data);
3003+ }
3004+};
3005+
3006+
3007+
3008+// Marionette.View
3009+// ---------------
3010+
3011+// The core view type that other Marionette views extend from.
3012+Marionette.View = Backbone.View.extend({
3013+
3014+ constructor: function(){
3015+ _.bindAll(this, "render");
3016+
3017+ var args = Array.prototype.slice.apply(arguments);
3018+ Backbone.View.prototype.constructor.apply(this, args);
3019+
3020+ Marionette.MonitorDOMRefresh(this);
3021+ this.listenTo(this, "show", this.onShowCalled, this);
3022+ },
3023+
3024+ // import the "triggerMethod" to trigger events with corresponding
3025+ // methods if the method exists
3026+ triggerMethod: Marionette.triggerMethod,
3027+
3028+ // Get the template for this view
3029+ // instance. You can set a `template` attribute in the view
3030+ // definition or pass a `template: "whatever"` parameter in
3031+ // to the constructor options.
3032+ getTemplate: function(){
3033+ return Marionette.getOption(this, "template");
3034+ },
3035+
3036+ // Mix in template helper methods. Looks for a
3037+ // `templateHelpers` attribute, which can either be an
3038+ // object literal, or a function that returns an object
3039+ // literal. All methods and attributes from this object
3040+ // are copies to the object passed in.
3041+ mixinTemplateHelpers: function(target){
3042+ target = target || {};
3043+ var templateHelpers = Marionette.getOption(this, "templateHelpers");
3044+ if (_.isFunction(templateHelpers)){
3045+ templateHelpers = templateHelpers.call(this);
3046+ }
3047+ return _.extend(target, templateHelpers);
3048+ },
3049+
3050+ // Configure `triggers` to forward DOM events to view
3051+ // events. `triggers: {"click .foo": "do:foo"}`
3052+ configureTriggers: function(){
3053+ if (!this.triggers) { return; }
3054+
3055+ var triggerEvents = {};
3056+
3057+ // Allow `triggers` to be configured as a function
3058+ var triggers = _.result(this, "triggers");
3059+
3060+ // Configure the triggers, prevent default
3061+ // action and stop propagation of DOM events
3062+ _.each(triggers, function(value, key){
3063+
3064+ // build the event handler function for the DOM event
3065+ triggerEvents[key] = function(e){
3066+
3067+ // stop the event in its tracks
3068+ if (e && e.preventDefault){ e.preventDefault(); }
3069+ if (e && e.stopPropagation){ e.stopPropagation(); }
3070+
3071+ // build the args for the event
3072+ var args = {
3073+ view: this,
3074+ model: this.model,
3075+ collection: this.collection
3076+ };
3077+
3078+ // trigger the event
3079+ this.triggerMethod(value, args);
3080+ };
3081+
3082+ }, this);
3083+
3084+ return triggerEvents;
3085+ },
3086+
3087+ // Overriding Backbone.View's delegateEvents to handle
3088+ // the `triggers`, `modelEvents`, and `collectionEvents` configuration
3089+ delegateEvents: function(events){
3090+ this._delegateDOMEvents(events);
3091+ Marionette.bindEntityEvents(this, this.model, Marionette.getOption(this, "modelEvents"));
3092+ Marionette.bindEntityEvents(this, this.collection, Marionette.getOption(this, "collectionEvents"));
3093+ },
3094+
3095+ // internal method to delegate DOM events and triggers
3096+ _delegateDOMEvents: function(events){
3097+ events = events || this.events;
3098+ if (_.isFunction(events)){ events = events.call(this); }
3099+
3100+ var combinedEvents = {};
3101+ var triggers = this.configureTriggers();
3102+ _.extend(combinedEvents, events, triggers);
3103+
3104+ Backbone.View.prototype.delegateEvents.call(this, combinedEvents);
3105+ },
3106+
3107+ // Overriding Backbone.View's undelegateEvents to handle unbinding
3108+ // the `triggers`, `modelEvents`, and `collectionEvents` config
3109+ undelegateEvents: function(){
3110+ var args = Array.prototype.slice.call(arguments);
3111+ Backbone.View.prototype.undelegateEvents.apply(this, args);
3112+
3113+ Marionette.unbindEntityEvents(this, this.model, Marionette.getOption(this, "modelEvents"));
3114+ Marionette.unbindEntityEvents(this, this.collection, Marionette.getOption(this, "collectionEvents"));
3115+ },
3116+
3117+ // Internal method, handles the `show` event.
3118+ onShowCalled: function(){},
3119+
3120+ // Default `close` implementation, for removing a view from the
3121+ // DOM and unbinding it. Regions will call this method
3122+ // for you. You can specify an `onClose` method in your view to
3123+ // add custom code that is called after the view is closed.
3124+ close: function(){
3125+ if (this.isClosed) { return; }
3126+
3127+ // allow the close to be stopped by returning `false`
3128+ // from the `onBeforeClose` method
3129+ var shouldClose = this.triggerMethod("before:close");
3130+ if (shouldClose === false){
3131+ return;
3132+ }
3133+
3134+ // mark as closed before doing the actual close, to
3135+ // prevent infinite loops within "close" event handlers
3136+ // that are trying to close other views
3137+ this.isClosed = true;
3138+ this.triggerMethod("close");
3139+
3140+ // unbind UI elements
3141+ this.unbindUIElements();
3142+
3143+ // remove the view from the DOM
3144+ this.remove();
3145+ },
3146+
3147+ // This method binds the elements specified in the "ui" hash inside the view's code with
3148+ // the associated jQuery selectors.
3149+ bindUIElements: function(){
3150+ if (!this.ui) { return; }
3151+
3152+ // store the ui hash in _uiBindings so they can be reset later
3153+ // and so re-rendering the view will be able to find the bindings
3154+ if (!this._uiBindings){
3155+ this._uiBindings = this.ui;
3156+ }
3157+
3158+ // get the bindings result, as a function or otherwise
3159+ var bindings = _.result(this, "_uiBindings");
3160+
3161+ // empty the ui so we don't have anything to start with
3162+ this.ui = {};
3163+
3164+ // bind each of the selectors
3165+ _.each(_.keys(bindings), function(key) {
3166+ var selector = bindings[key];
3167+ this.ui[key] = this.$(selector);
3168+ }, this);
3169+ },
3170+
3171+ // This method unbinds the elements specified in the "ui" hash
3172+ unbindUIElements: function(){
3173+ if (!this.ui || !this._uiBindings){ return; }
3174+
3175+ // delete all of the existing ui bindings
3176+ _.each(this.ui, function($el, name){
3177+ delete this.ui[name];
3178+ }, this);
3179+
3180+ // reset the ui element to the original bindings configuration
3181+ this.ui = this._uiBindings;
3182+ delete this._uiBindings;
3183+ }
3184+});
3185+
3186+// Item View
3187+// ---------
3188+
3189+// A single item view implementation that contains code for rendering
3190+// with underscore.js templates, serializing the view's model or collection,
3191+// and calling several methods on extended views, such as `onRender`.
3192+Marionette.ItemView = Marionette.View.extend({
3193+
3194+ // Setting up the inheritance chain which allows changes to
3195+ // Marionette.View.prototype.constructor which allows overriding
3196+ constructor: function(){
3197+ Marionette.View.prototype.constructor.apply(this, slice(arguments));
3198+ },
3199+
3200+ // Serialize the model or collection for the view. If a model is
3201+ // found, `.toJSON()` is called. If a collection is found, `.toJSON()`
3202+ // is also called, but is used to populate an `items` array in the
3203+ // resulting data. If both are found, defaults to the model.
3204+ // You can override the `serializeData` method in your own view
3205+ // definition, to provide custom serialization for your view's data.
3206+ serializeData: function(){
3207+ var data = {};
3208+
3209+ if (this.model) {
3210+ data = this.model.toJSON();
3211+ }
3212+ else if (this.collection) {
3213+ data = { items: this.collection.toJSON() };
3214+ }
3215+
3216+ return data;
3217+ },
3218+
3219+ // Render the view, defaulting to underscore.js templates.
3220+ // You can override this in your view definition to provide
3221+ // a very specific rendering for your view. In general, though,
3222+ // you should override the `Marionette.Renderer` object to
3223+ // change how Marionette renders views.
3224+ render: function(){
3225+ this.isClosed = false;
3226+
3227+ this.triggerMethod("before:render", this);
3228+ this.triggerMethod("item:before:render", this);
3229+
3230+ var data = this.serializeData();
3231+ data = this.mixinTemplateHelpers(data);
3232+
3233+ var template = this.getTemplate();
3234+ var html = Marionette.Renderer.render(template, data);
3235+
3236+ this.$el.html(html);
3237+ this.bindUIElements();
3238+
3239+ this.triggerMethod("render", this);
3240+ this.triggerMethod("item:rendered", this);
3241+
3242+ return this;
3243+ },
3244+
3245+ // Override the default close event to add a few
3246+ // more events that are triggered.
3247+ close: function(){
3248+ if (this.isClosed){ return; }
3249+
3250+ this.triggerMethod('item:before:close');
3251+
3252+ Marionette.View.prototype.close.apply(this, slice(arguments));
3253+
3254+ this.triggerMethod('item:closed');
3255+ }
3256+});
3257+
3258+// Collection View
3259+// ---------------
3260+
3261+// A view that iterates over a Backbone.Collection
3262+// and renders an individual ItemView for each model.
3263+Marionette.CollectionView = Marionette.View.extend({
3264+ // used as the prefix for item view events
3265+ // that are forwarded through the collectionview
3266+ itemViewEventPrefix: "itemview",
3267+
3268+ // constructor
3269+ constructor: function(options){
3270+ this._initChildViewStorage();
3271+
3272+ Marionette.View.prototype.constructor.apply(this, slice(arguments));
3273+
3274+ this._initialEvents();
3275+ },
3276+
3277+ // Configured the initial events that the collection view
3278+ // binds to. Override this method to prevent the initial
3279+ // events, or to add your own initial events.
3280+ _initialEvents: function(){
3281+ if (this.collection){
3282+ this.listenTo(this.collection, "add", this.addChildView, this);
3283+ this.listenTo(this.collection, "remove", this.removeItemView, this);
3284+ this.listenTo(this.collection, "reset", this.render, this);
3285+ }
3286+ },
3287+
3288+ // Handle a child item added to the collection
3289+ addChildView: function(item, collection, options){
3290+ this.closeEmptyView();
3291+ var ItemView = this.getItemView(item);
3292+ var index = this.collection.indexOf(item);
3293+ this.addItemView(item, ItemView, index);
3294+ },
3295+
3296+ // Override from `Marionette.View` to guarantee the `onShow` method
3297+ // of child views is called.
3298+ onShowCalled: function(){
3299+ this.children.each(function(child){
3300+ Marionette.triggerMethod.call(child, "show");
3301+ });
3302+ },
3303+
3304+ // Internal method to trigger the before render callbacks
3305+ // and events
3306+ triggerBeforeRender: function(){
3307+ this.triggerMethod("before:render", this);
3308+ this.triggerMethod("collection:before:render", this);
3309+ },
3310+
3311+ // Internal method to trigger the rendered callbacks and
3312+ // events
3313+ triggerRendered: function(){
3314+ this.triggerMethod("render", this);
3315+ this.triggerMethod("collection:rendered", this);
3316+ },
3317+
3318+ // Render the collection of items. Override this method to
3319+ // provide your own implementation of a render function for
3320+ // the collection view.
3321+ render: function(){
3322+ this.isClosed = false;
3323+ this.triggerBeforeRender();
3324+ this._renderChildren();
3325+ this.triggerRendered();
3326+ return this;
3327+ },
3328+
3329+ // Internal method. Separated so that CompositeView can have
3330+ // more control over events being triggered, around the rendering
3331+ // process
3332+ _renderChildren: function(){
3333+ this.closeEmptyView();
3334+ this.closeChildren();
3335+
3336+ if (this.collection && this.collection.length > 0) {
3337+ this.showCollection();
3338+ } else {
3339+ this.showEmptyView();
3340+ }
3341+ },
3342+
3343+ // Internal method to loop through each item in the
3344+ // collection view and show it
3345+ showCollection: function(){
3346+ var ItemView;
3347+ this.collection.each(function(item, index){
3348+ ItemView = this.getItemView(item);
3349+ this.addItemView(item, ItemView, index);
3350+ }, this);
3351+ },
3352+
3353+ // Internal method to show an empty view in place of
3354+ // a collection of item views, when the collection is
3355+ // empty
3356+ showEmptyView: function(){
3357+ var EmptyView = Marionette.getOption(this, "emptyView");
3358+
3359+ if (EmptyView && !this._showingEmptyView){
3360+ this._showingEmptyView = true;
3361+ var model = new Backbone.Model();
3362+ this.addItemView(model, EmptyView, 0);
3363+ }
3364+ },
3365+
3366+ // Internal method to close an existing emptyView instance
3367+ // if one exists. Called when a collection view has been
3368+ // rendered empty, and then an item is added to the collection.
3369+ closeEmptyView: function(){
3370+ if (this._showingEmptyView){
3371+ this.closeChildren();
3372+ delete this._showingEmptyView;
3373+ }
3374+ },
3375+
3376+ // Retrieve the itemView type, either from `this.options.itemView`
3377+ // or from the `itemView` in the object definition. The "options"
3378+ // takes precedence.
3379+ getItemView: function(item){
3380+ var itemView = Marionette.getOption(this, "itemView");
3381+
3382+ if (!itemView){
3383+ throwError("An `itemView` must be specified", "NoItemViewError");
3384+ }
3385+
3386+ return itemView;
3387+ },
3388+
3389+ // Render the child item's view and add it to the
3390+ // HTML for the collection view.
3391+ addItemView: function(item, ItemView, index){
3392+ // get the itemViewOptions if any were specified
3393+ var itemViewOptions = Marionette.getOption(this, "itemViewOptions");
3394+ if (_.isFunction(itemViewOptions)){
3395+ itemViewOptions = itemViewOptions.call(this, item, index);
3396+ }
3397+
3398+ // build the view
3399+ var view = this.buildItemView(item, ItemView, itemViewOptions);
3400+
3401+ // set up the child view event forwarding
3402+ this.addChildViewEventForwarding(view);
3403+
3404+ // this view is about to be added
3405+ this.triggerMethod("before:item:added", view);
3406+
3407+ // Store the child view itself so we can properly
3408+ // remove and/or close it later
3409+ this.children.add(view);
3410+
3411+ // Render it and show it
3412+ this.renderItemView(view, index);
3413+
3414+ // call the "show" method if the collection view
3415+ // has already been shown
3416+ if (this._isShown){
3417+ Marionette.triggerMethod.call(view, "show");
3418+ }
3419+
3420+ // this view was added
3421+ this.triggerMethod("after:item:added", view);
3422+ },
3423+
3424+ // Set up the child view event forwarding. Uses an "itemview:"
3425+ // prefix in front of all forwarded events.
3426+ addChildViewEventForwarding: function(view){
3427+ var prefix = Marionette.getOption(this, "itemViewEventPrefix");
3428+
3429+ // Forward all child item view events through the parent,
3430+ // prepending "itemview:" to the event name
3431+ this.listenTo(view, "all", function(){
3432+ var args = slice(arguments);
3433+ args[0] = prefix + ":" + args[0];
3434+ args.splice(1, 0, view);
3435+
3436+ Marionette.triggerMethod.apply(this, args);
3437+ }, this);
3438+ },
3439+
3440+ // render the item view
3441+ renderItemView: function(view, index) {
3442+ view.render();
3443+ this.appendHtml(this, view, index);
3444+ },
3445+
3446+ // Build an `itemView` for every model in the collection.
3447+ buildItemView: function(item, ItemViewType, itemViewOptions){
3448+ var options = _.extend({model: item}, itemViewOptions);
3449+ return new ItemViewType(options);
3450+ },
3451+
3452+ // get the child view by item it holds, and remove it
3453+ removeItemView: function(item){
3454+ var view = this.children.findByModel(item);
3455+ this.removeChildView(view);
3456+ this.checkEmpty();
3457+ },
3458+
3459+ // Remove the child view and close it
3460+ removeChildView: function(view){
3461+
3462+ // shut down the child view properly,
3463+ // including events that the collection has from it
3464+ if (view){
3465+ this.stopListening(view);
3466+
3467+ // call 'close' or 'remove', depending on which is found
3468+ if (view.close) { view.close(); }
3469+ else if (view.remove) { view.remove(); }
3470+
3471+ this.children.remove(view);
3472+ }
3473+
3474+ this.triggerMethod("item:removed", view);
3475+ },
3476+
3477+ // helper to show the empty view if the collection is empty
3478+ checkEmpty: function() {
3479+ // check if we're empty now, and if we are, show the
3480+ // empty view
3481+ if (!this.collection || this.collection.length === 0){
3482+ this.showEmptyView();
3483+ }
3484+ },
3485+
3486+ // Append the HTML to the collection's `el`.
3487+ // Override this method to do something other
3488+ // then `.append`.
3489+ appendHtml: function(collectionView, itemView, index){
3490+ collectionView.$el.append(itemView.el);
3491+ },
3492+
3493+ // Internal method to set up the `children` object for
3494+ // storing all of the child views
3495+ _initChildViewStorage: function(){
3496+ this.children = new Backbone.ChildViewContainer();
3497+ },
3498+
3499+ // Handle cleanup and other closing needs for
3500+ // the collection of views.
3501+ close: function(){
3502+ if (this.isClosed){ return; }
3503+
3504+ this.triggerMethod("collection:before:close");
3505+ this.closeChildren();
3506+ this.triggerMethod("collection:closed");
3507+
3508+ Marionette.View.prototype.close.apply(this, slice(arguments));
3509+ },
3510+
3511+ // Close the child views that this collection view
3512+ // is holding on to, if any
3513+ closeChildren: function(){
3514+ this.children.each(function(child){
3515+ this.removeChildView(child);
3516+ }, this);
3517+ this.checkEmpty();
3518+ }
3519+});
3520+
3521+
3522+// Composite View
3523+// --------------
3524+
3525+// Used for rendering a branch-leaf, hierarchical structure.
3526+// Extends directly from CollectionView and also renders an
3527+// an item view as `modelView`, for the top leaf
3528+Marionette.CompositeView = Marionette.CollectionView.extend({
3529+
3530+ // Setting up the inheritance chain which allows changes to
3531+ // Marionette.CollectionView.prototype.constructor which allows overriding
3532+ constructor: function(){
3533+ Marionette.CollectionView.prototype.constructor.apply(this, slice(arguments));
3534+ },
3535+
3536+ // Configured the initial events that the composite view
3537+ // binds to. Override this method to prevent the initial
3538+ // events, or to add your own initial events.
3539+ _initialEvents: function(){
3540+ if (this.collection){
3541+ this.listenTo(this.collection, "add", this.addChildView, this);
3542+ this.listenTo(this.collection, "remove", this.removeItemView, this);
3543+ this.listenTo(this.collection, "reset", this._renderChildren, this);
3544+ }
3545+ },
3546+
3547+ // Retrieve the `itemView` to be used when rendering each of
3548+ // the items in the collection. The default is to return
3549+ // `this.itemView` or Marionette.CompositeView if no `itemView`
3550+ // has been defined
3551+ getItemView: function(item){
3552+ var itemView = Marionette.getOption(this, "itemView") || this.constructor;
3553+
3554+ if (!itemView){
3555+ throwError("An `itemView` must be specified", "NoItemViewError");
3556+ }
3557+
3558+ return itemView;
3559+ },
3560+
3561+ // Serialize the collection for the view.
3562+ // You can override the `serializeData` method in your own view
3563+ // definition, to provide custom serialization for your view's data.
3564+ serializeData: function(){
3565+ var data = {};
3566+
3567+ if (this.model){
3568+ data = this.model.toJSON();
3569+ }
3570+
3571+ return data;
3572+ },
3573+
3574+ // Renders the model once, and the collection once. Calling
3575+ // this again will tell the model's view to re-render itself
3576+ // but the collection will not re-render.
3577+ render: function(){
3578+ this.isRendered = true;
3579+ this.isClosed = false;
3580+ this.resetItemViewContainer();
3581+
3582+ this.triggerBeforeRender();
3583+ var html = this.renderModel();
3584+ this.$el.html(html);
3585+ // the ui bindings is done here and not at the end of render since they
3586+ // will not be available until after the model is rendered, but should be
3587+ // available before the collection is rendered.
3588+ this.bindUIElements();
3589+ this.triggerMethod("composite:model:rendered");
3590+
3591+ this._renderChildren();
3592+
3593+ this.triggerMethod("composite:rendered");
3594+ this.triggerRendered();
3595+ return this;
3596+ },
3597+
3598+ _renderChildren: function(){
3599+ if (this.isRendered){
3600+ Marionette.CollectionView.prototype._renderChildren.call(this);
3601+ this.triggerMethod("composite:collection:rendered");
3602+ }
3603+ },
3604+
3605+ // Render an individual model, if we have one, as
3606+ // part of a composite view (branch / leaf). For example:
3607+ // a treeview.
3608+ renderModel: function(){
3609+ var data = {};
3610+ data = this.serializeData();
3611+ data = this.mixinTemplateHelpers(data);
3612+
3613+ var template = this.getTemplate();
3614+ return Marionette.Renderer.render(template, data);
3615+ },
3616+
3617+ // Appends the `el` of itemView instances to the specified
3618+ // `itemViewContainer` (a jQuery selector). Override this method to
3619+ // provide custom logic of how the child item view instances have their
3620+ // HTML appended to the composite view instance.
3621+ appendHtml: function(cv, iv, index){
3622+ var $container = this.getItemViewContainer(cv);
3623+ $container.append(iv.el);
3624+ },
3625+
3626+ // Internal method to ensure an `$itemViewContainer` exists, for the
3627+ // `appendHtml` method to use.
3628+ getItemViewContainer: function(containerView){
3629+ if ("$itemViewContainer" in containerView){
3630+ return containerView.$itemViewContainer;
3631+ }
3632+
3633+ var container;
3634+ var itemViewContainer = Marionette.getOption(containerView, "itemViewContainer");
3635+ if (itemViewContainer){
3636+
3637+ var selector = _.isFunction(itemViewContainer) ? itemViewContainer() : itemViewContainer;
3638+ container = containerView.$(selector);
3639+ if (container.length <= 0) {
3640+ throwError("The specified `itemViewContainer` was not found: " + containerView.itemViewContainer, "ItemViewContainerMissingError");
3641+ }
3642+
3643+ } else {
3644+ container = containerView.$el;
3645+ }
3646+
3647+ containerView.$itemViewContainer = container;
3648+ return container;
3649+ },
3650+
3651+ // Internal method to reset the `$itemViewContainer` on render
3652+ resetItemViewContainer: function(){
3653+ if (this.$itemViewContainer){
3654+ delete this.$itemViewContainer;
3655+ }
3656+ }
3657+});
3658+
3659+
3660+// Layout
3661+// ------
3662+
3663+// Used for managing application layouts, nested layouts and
3664+// multiple regions within an application or sub-application.
3665+//
3666+// A specialized view type that renders an area of HTML and then
3667+// attaches `Region` instances to the specified `regions`.
3668+// Used for composite view management and sub-application areas.
3669+Marionette.Layout = Marionette.ItemView.extend({
3670+ regionType: Marionette.Region,
3671+
3672+ // Ensure the regions are available when the `initialize` method
3673+ // is called.
3674+ constructor: function (options) {
3675+ options = options || {};
3676+
3677+ this._firstRender = true;
3678+ this._initializeRegions(options);
3679+
3680+ Marionette.ItemView.prototype.constructor.call(this, options);
3681+ },
3682+
3683+ // Layout's render will use the existing region objects the
3684+ // first time it is called. Subsequent calls will close the
3685+ // views that the regions are showing and then reset the `el`
3686+ // for the regions to the newly rendered DOM elements.
3687+ render: function(){
3688+
3689+ if (this.isClosed){
3690+ // a previously closed layout means we need to
3691+ // completely re-initialize the regions
3692+ this._initializeRegions();
3693+ }
3694+ if (this._firstRender) {
3695+ // if this is the first render, don't do anything to
3696+ // reset the regions
3697+ this._firstRender = false;
3698+ } else if (!this.isClosed){
3699+ // If this is not the first render call, then we need to
3700+ // re-initializing the `el` for each region
3701+ this._reInitializeRegions();
3702+ }
3703+
3704+ var args = Array.prototype.slice.apply(arguments);
3705+ var result = Marionette.ItemView.prototype.render.apply(this, args);
3706+
3707+ return result;
3708+ },
3709+
3710+ // Handle closing regions, and then close the view itself.
3711+ close: function () {
3712+ if (this.isClosed){ return; }
3713+ this.regionManager.close();
3714+ var args = Array.prototype.slice.apply(arguments);
3715+ Marionette.ItemView.prototype.close.apply(this, args);
3716+ },
3717+
3718+ // Add a single region, by name, to the layout
3719+ addRegion: function(name, definition){
3720+ var regions = {};
3721+ regions[name] = definition;
3722+ return this._buildRegions(regions)[name];
3723+ },
3724+
3725+ // Add multiple regions as a {name: definition, name2: def2} object literal
3726+ addRegions: function(regions){
3727+ this.regions = _.extend({}, this.regions, regions);
3728+ return this._buildRegions(regions);
3729+ },
3730+
3731+ // Remove a single region from the Layout, by name
3732+ removeRegion: function(name){
3733+ delete this.regions[name];
3734+ return this.regionManager.removeRegion(name);
3735+ },
3736+
3737+ // internal method to build regions
3738+ _buildRegions: function(regions){
3739+ var that = this;
3740+
3741+ var defaults = {
3742+ regionType: Marionette.getOption(this, "regionType"),
3743+ parentEl: function(){ return that.$el; }
3744+ };
3745+
3746+ return this.regionManager.addRegions(regions, defaults);
3747+ },
3748+
3749+ // Internal method to initialize the regions that have been defined in a
3750+ // `regions` attribute on this layout.
3751+ _initializeRegions: function (options) {
3752+ var regions;
3753+ this._initRegionManager();
3754+
3755+ if (_.isFunction(this.regions)) {
3756+ regions = this.regions(options);
3757+ } else {
3758+ regions = this.regions || {};
3759+ }
3760+
3761+ this.addRegions(regions);
3762+ },
3763+
3764+ // Internal method to re-initialize all of the regions by updating the `el` that
3765+ // they point to
3766+ _reInitializeRegions: function(){
3767+ this.regionManager.closeRegions();
3768+ this.regionManager.each(function(region){
3769+ region.reset();
3770+ });
3771+ },
3772+
3773+ // Internal method to initialize the region manager
3774+ // and all regions in it
3775+ _initRegionManager: function(){
3776+ this.regionManager = new Marionette.RegionManager();
3777+
3778+ this.listenTo(this.regionManager, "region:add", function(name, region){
3779+ this[name] = region;
3780+ this.trigger("region:add", name, region);
3781+ });
3782+
3783+ this.listenTo(this.regionManager, "region:remove", function(name, region){
3784+ delete this[name];
3785+ this.trigger("region:remove", name, region);
3786+ });
3787+ }
3788+});
3789+
3790+
3791+// AppRouter
3792+// ---------
3793+
3794+// Reduce the boilerplate code of handling route events
3795+// and then calling a single method on another object.
3796+// Have your routers configured to call the method on
3797+// your object, directly.
3798+//
3799+// Configure an AppRouter with `appRoutes`.
3800+//
3801+// App routers can only take one `controller` object.
3802+// It is recommended that you divide your controller
3803+// objects in to smaller pieces of related functionality
3804+// and have multiple routers / controllers, instead of
3805+// just one giant router and controller.
3806+//
3807+// You can also add standard routes to an AppRouter.
3808+
3809+Marionette.AppRouter = Backbone.Router.extend({
3810+
3811+ constructor: function(options){
3812+ Backbone.Router.prototype.constructor.apply(this, slice(arguments));
3813+
3814+ this.options = options || {};
3815+
3816+ var appRoutes = Marionette.getOption(this, "appRoutes");
3817+ var controller = this._getController();
3818+ this.processAppRoutes(controller, appRoutes);
3819+ },
3820+
3821+ // Similar to route method on a Backbone Router but
3822+ // method is called on the controller
3823+ appRoute: function(route, methodName) {
3824+ var controller = this._getController();
3825+ this._addAppRoute(controller, route, methodName);
3826+ },
3827+
3828+ // Internal method to process the `appRoutes` for the
3829+ // router, and turn them in to routes that trigger the
3830+ // specified method on the specified `controller`.
3831+ processAppRoutes: function(controller, appRoutes) {
3832+ if (!appRoutes){ return; }
3833+
3834+ var routeNames = _.keys(appRoutes).reverse(); // Backbone requires reverted order of routes
3835+
3836+ _.each(routeNames, function(route) {
3837+ this._addAppRoute(controller, route, appRoutes[route]);
3838+ }, this);
3839+ },
3840+
3841+ _getController: function(){
3842+ return Marionette.getOption(this, "controller");
3843+ },
3844+
3845+ _addAppRoute: function(controller, route, methodName){
3846+ var method = controller[methodName];
3847+
3848+ if (!method) {
3849+ throw new Error("Method '" + methodName + "' was not found on the controller");
3850+ }
3851+
3852+ this.route(route, methodName, _.bind(method, controller));
3853+ }
3854+});
3855+
3856+
3857+// Application
3858+// -----------
3859+
3860+// Contain and manage the composite application as a whole.
3861+// Stores and starts up `Region` objects, includes an
3862+// event aggregator as `app.vent`
3863+Marionette.Application = function(options){
3864+ this._initRegionManager();
3865+ this._initCallbacks = new Marionette.Callbacks();
3866+ this.vent = new Backbone.Wreqr.EventAggregator();
3867+ this.commands = new Backbone.Wreqr.Commands();
3868+ this.reqres = new Backbone.Wreqr.RequestResponse();
3869+ this.submodules = {};
3870+
3871+ _.extend(this, options);
3872+
3873+ this.triggerMethod = Marionette.triggerMethod;
3874+};
3875+
3876+_.extend(Marionette.Application.prototype, Backbone.Events, {
3877+ // Command execution, facilitated by Backbone.Wreqr.Commands
3878+ execute: function(){
3879+ var args = Array.prototype.slice.apply(arguments);
3880+ this.commands.execute.apply(this.commands, args);
3881+ },
3882+
3883+ // Request/response, facilitated by Backbone.Wreqr.RequestResponse
3884+ request: function(){
3885+ var args = Array.prototype.slice.apply(arguments);
3886+ return this.reqres.request.apply(this.reqres, args);
3887+ },
3888+
3889+ // Add an initializer that is either run at when the `start`
3890+ // method is called, or run immediately if added after `start`
3891+ // has already been called.
3892+ addInitializer: function(initializer){
3893+ this._initCallbacks.add(initializer);
3894+ },
3895+
3896+ // kick off all of the application's processes.
3897+ // initializes all of the regions that have been added
3898+ // to the app, and runs all of the initializer functions
3899+ start: function(options){
3900+ this.triggerMethod("initialize:before", options);
3901+ this._initCallbacks.run(options, this);
3902+ this.triggerMethod("initialize:after", options);
3903+
3904+ this.triggerMethod("start", options);
3905+ },
3906+
3907+ // Add regions to your app.
3908+ // Accepts a hash of named strings or Region objects
3909+ // addRegions({something: "#someRegion"})
3910+ // addRegions({something: Region.extend({el: "#someRegion"}) });
3911+ addRegions: function(regions){
3912+ return this._regionManager.addRegions(regions);
3913+ },
3914+
3915+ // Close all regions in the app, without removing them
3916+ closeRegions: function(){
3917+ this._regionManager.closeRegions();
3918+ },
3919+
3920+ // Removes a region from your app, by name
3921+ // Accepts the regions name
3922+ // removeRegion('myRegion')
3923+ removeRegion: function(region) {
3924+ this._regionManager.removeRegion(region);
3925+ },
3926+
3927+ // Provides alternative access to regions
3928+ // Accepts the region name
3929+ // getRegion('main')
3930+ getRegion: function(region) {
3931+ return this._regionManager.get(region);
3932+ },
3933+
3934+ // Create a module, attached to the application
3935+ module: function(moduleNames, moduleDefinition){
3936+ // slice the args, and add this application object as the
3937+ // first argument of the array
3938+ var args = slice(arguments);
3939+ args.unshift(this);
3940+
3941+ // see the Marionette.Module object for more information
3942+ return Marionette.Module.create.apply(Marionette.Module, args);
3943+ },
3944+
3945+ // Internal method to set up the region manager
3946+ _initRegionManager: function(){
3947+ this._regionManager = new Marionette.RegionManager();
3948+
3949+ this.listenTo(this._regionManager, "region:add", function(name, region){
3950+ this[name] = region;
3951+ });
3952+
3953+ this.listenTo(this._regionManager, "region:remove", function(name, region){
3954+ delete this[name];
3955+ });
3956+ }
3957+});
3958+
3959+// Copy the `extend` function used by Backbone's classes
3960+Marionette.Application.extend = Marionette.extend;
3961+
3962+// Module
3963+// ------
3964+
3965+// A simple module system, used to create privacy and encapsulation in
3966+// Marionette applications
3967+Marionette.Module = function(moduleName, app){
3968+ this.moduleName = moduleName;
3969+
3970+ // store sub-modules
3971+ this.submodules = {};
3972+
3973+ this._setupInitializersAndFinalizers();
3974+
3975+ // store the configuration for this module
3976+ this.app = app;
3977+ this.startWithParent = true;
3978+
3979+ this.triggerMethod = Marionette.triggerMethod;
3980+};
3981+
3982+// Extend the Module prototype with events / listenTo, so that the module
3983+// can be used as an event aggregator or pub/sub.
3984+_.extend(Marionette.Module.prototype, Backbone.Events, {
3985+
3986+ // Initializer for a specific module. Initializers are run when the
3987+ // module's `start` method is called.
3988+ addInitializer: function(callback){
3989+ this._initializerCallbacks.add(callback);
3990+ },
3991+
3992+ // Finalizers are run when a module is stopped. They are used to teardown
3993+ // and finalize any variables, references, events and other code that the
3994+ // module had set up.
3995+ addFinalizer: function(callback){
3996+ this._finalizerCallbacks.add(callback);
3997+ },
3998+
3999+ // Start the module, and run all of its initializers
4000+ start: function(options){
4001+ // Prevent re-starting a module that is already started
4002+ if (this._isInitialized){ return; }
4003+
4004+ // start the sub-modules (depth-first hierarchy)
4005+ _.each(this.submodules, function(mod){
4006+ // check to see if we should start the sub-module with this parent
4007+ if (mod.startWithParent){
4008+ mod.start(options);
4009+ }
4010+ });
4011+
4012+ // run the callbacks to "start" the current module
4013+ this.triggerMethod("before:start", options);
4014+
4015+ this._initializerCallbacks.run(options, this);
4016+ this._isInitialized = true;
4017+
4018+ this.triggerMethod("start", options);
4019+ },
4020+
4021+ // Stop this module by running its finalizers and then stop all of
4022+ // the sub-modules for this module
4023+ stop: function(){
4024+ // if we are not initialized, don't bother finalizing
4025+ if (!this._isInitialized){ return; }
4026+ this._isInitialized = false;
4027+
4028+ Marionette.triggerMethod.call(this, "before:stop");
4029+
4030+ // stop the sub-modules; depth-first, to make sure the
4031+ // sub-modules are stopped / finalized before parents
4032+ _.each(this.submodules, function(mod){ mod.stop(); });
4033+
4034+ // run the finalizers
4035+ this._finalizerCallbacks.run(undefined,this);
4036+
4037+ // reset the initializers and finalizers
4038+ this._initializerCallbacks.reset();
4039+ this._finalizerCallbacks.reset();
4040+
4041+ Marionette.triggerMethod.call(this, "stop");
4042+ },
4043+
4044+ // Configure the module with a definition function and any custom args
4045+ // that are to be passed in to the definition function
4046+ addDefinition: function(moduleDefinition, customArgs){
4047+ this._runModuleDefinition(moduleDefinition, customArgs);
4048+ },
4049+
4050+ // Internal method: run the module definition function with the correct
4051+ // arguments
4052+ _runModuleDefinition: function(definition, customArgs){
4053+ if (!definition){ return; }
4054+
4055+ // build the correct list of arguments for the module definition
4056+ var args = _.flatten([
4057+ this,
4058+ this.app,
4059+ Backbone,
4060+ Marionette,
4061+ Marionette.$, _,
4062+ customArgs
4063+ ]);
4064+
4065+ definition.apply(this, args);
4066+ },
4067+
4068+ // Internal method: set up new copies of initializers and finalizers.
4069+ // Calling this method will wipe out all existing initializers and
4070+ // finalizers.
4071+ _setupInitializersAndFinalizers: function(){
4072+ this._initializerCallbacks = new Marionette.Callbacks();
4073+ this._finalizerCallbacks = new Marionette.Callbacks();
4074+ }
4075+});
4076+
4077+// Type methods to create modules
4078+_.extend(Marionette.Module, {
4079+
4080+ // Create a module, hanging off the app parameter as the parent object.
4081+ create: function(app, moduleNames, moduleDefinition){
4082+ var module = app;
4083+
4084+ // get the custom args passed in after the module definition and
4085+ // get rid of the module name and definition function
4086+ var customArgs = slice(arguments);
4087+ customArgs.splice(0, 3);
4088+
4089+ // split the module names and get the length
4090+ moduleNames = moduleNames.split(".");
4091+ var length = moduleNames.length;
4092+
4093+ // store the module definition for the last module in the chain
4094+ var moduleDefinitions = [];
4095+ moduleDefinitions[length-1] = moduleDefinition;
4096+
4097+ // Loop through all the parts of the module definition
4098+ _.each(moduleNames, function(moduleName, i){
4099+ var parentModule = module;
4100+ module = this._getModule(parentModule, moduleName, app);
4101+ this._addModuleDefinition(parentModule, module, moduleDefinitions[i], customArgs);
4102+ }, this);
4103+
4104+ // Return the last module in the definition chain
4105+ return module;
4106+ },
4107+
4108+ _getModule: function(parentModule, moduleName, app, def, args){
4109+ // Get an existing module of this name if we have one
4110+ var module = parentModule[moduleName];
4111+
4112+ if (!module){
4113+ // Create a new module if we don't have one
4114+ module = new Marionette.Module(moduleName, app);
4115+ parentModule[moduleName] = module;
4116+ // store the module on the parent
4117+ parentModule.submodules[moduleName] = module;
4118+ }
4119+
4120+ return module;
4121+ },
4122+
4123+ _addModuleDefinition: function(parentModule, module, def, args){
4124+ var fn;
4125+ var startWithParent;
4126+
4127+ if (_.isFunction(def)){
4128+ // if a function is supplied for the module definition
4129+ fn = def;
4130+ startWithParent = true;
4131+
4132+ } else if (_.isObject(def)){
4133+ // if an object is supplied
4134+ fn = def.define;
4135+ startWithParent = def.startWithParent;
4136+
4137+ } else {
4138+ // if nothing is supplied
4139+ startWithParent = true;
4140+ }
4141+
4142+ // add module definition if needed
4143+ if (fn){
4144+ module.addDefinition(fn, args);
4145+ }
4146+
4147+ // `and` the two together, ensuring a single `false` will prevent it
4148+ // from starting with the parent
4149+ module.startWithParent = module.startWithParent && startWithParent;
4150+
4151+ // setup auto-start if needed
4152+ if (module.startWithParent && !module.startWithParentIsConfigured){
4153+
4154+ // only configure this once
4155+ module.startWithParentIsConfigured = true;
4156+
4157+ // add the module initializer config
4158+ parentModule.addInitializer(function(options){
4159+ if (module.startWithParent){
4160+ module.start(options);
4161+ }
4162+ });
4163+
4164+ }
4165+
4166+ }
4167+});
4168+
4169+
4170+
4171+ return Marionette;
4172+})(this, Backbone, _);
4173\ No newline at end of file
4174
4175=== added directory 'web_unleashed/static/lib/underscore'
4176=== added directory 'web_unleashed/static/lib/underscore-addons'
4177=== added file 'web_unleashed/static/lib/underscore-addons/underscore.deep_extend.js'
4178--- web_unleashed/static/lib/underscore-addons/underscore.deep_extend.js 1970-01-01 00:00:00 +0000
4179+++ web_unleashed/static/lib/underscore-addons/underscore.deep_extend.js 2014-01-28 13:12:54 +0000
4180@@ -0,0 +1,52 @@
4181+/* Copyright (C) 2012-2013 Kurt Milam - http://xioup.com | Source: https://gist.github.com/1868955
4182+ *
4183+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4184+ * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
4185+ *
4186+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
4187+**/
4188+
4189+// Based conceptually on the _.extend() function in underscore.js ( see http://documentcloud.github.com/underscore/#extend for more details )
4190+
4191+// source: https://gist.github.com/kurtmilam/1868955
4192+
4193+(function(Underscore){
4194+ var _ = Underscore;
4195+ var deepExtend = function(obj) {
4196+ var parentRE = /#{\s*?_\s*?}/, slice = Array.prototype.slice, hasOwnProperty = Object.prototype.hasOwnProperty;
4197+
4198+ _.each(slice.call(arguments, 1), function(source) {
4199+ for (var prop in source) {
4200+ if (hasOwnProperty.call(source, prop)) {
4201+ if (_.isUndefined(obj[prop]) || _.isFunction(obj[prop]) || _.isNull(source[prop])) {
4202+ obj[prop] = source[prop];
4203+ } else if (_.isString(source[prop]) && parentRE.test(source[prop])) {
4204+ if (_.isString(obj[prop])) {
4205+ obj[prop] = source[prop].replace(parentRE, obj[prop]);
4206+ }
4207+ } else if (_.isArray(obj[prop]) || _.isArray(source[prop])) {
4208+ if (!_.isArray(obj[prop]) || !_.isArray(source[prop])) {
4209+ throw 'Error: Trying to combine an array with a non-array (' + prop + ')';
4210+ } else {
4211+ obj[prop] = _.reject(_.deepExtend(obj[prop], source[prop]), function(item) {
4212+ return _.isNull(item);
4213+ });
4214+ }
4215+ } else if (_.isObject(obj[prop]) || _.isObject(source[prop])) {
4216+ if (!_.isObject(obj[prop]) || !_.isObject(source[prop])) {
4217+ throw 'Error: Trying to combine an object with a non-object (' + prop + ')';
4218+ } else {
4219+ obj[prop] = _.deepExtend(obj[prop], source[prop]);
4220+ }
4221+ } else {
4222+ obj[prop] = source[prop];
4223+ }
4224+ }
4225+ }
4226+ });
4227+ return obj;
4228+ };
4229+
4230+ Underscore.mixin({deepExtend: deepExtend});
4231+
4232+})(_ || Underscore)
4233\ No newline at end of file
4234
4235=== added file 'web_unleashed/static/lib/underscore-addons/underscore.find_index_where.js'
4236--- web_unleashed/static/lib/underscore-addons/underscore.find_index_where.js 1970-01-01 00:00:00 +0000
4237+++ web_unleashed/static/lib/underscore-addons/underscore.find_index_where.js 2014-01-28 13:12:54 +0000
4238@@ -0,0 +1,25 @@
4239+(function(Underscore) {
4240+ var _ = Underscore;
4241+ var findIndexWhere = function(obj, find) {
4242+
4243+ var index = null, name;
4244+ _.each(obj, function(item, i) {
4245+ var found = true;
4246+ for(name in find){
4247+ if(item[name] !== find[name]){
4248+ found = false;
4249+ }
4250+ }
4251+ if(found){
4252+ index = i;
4253+ }
4254+ });
4255+
4256+ return obj;
4257+ };
4258+
4259+ Underscore.mixin({
4260+ findIndexWhere : findIndexWhere
4261+ });
4262+
4263+})(_ || Underscore)
4264\ No newline at end of file
4265
4266=== added file 'web_unleashed/static/lib/underscore/underscore.js'
4267--- web_unleashed/static/lib/underscore/underscore.js 1970-01-01 00:00:00 +0000
4268+++ web_unleashed/static/lib/underscore/underscore.js 2014-01-28 13:12:54 +0000
4269@@ -0,0 +1,1276 @@
4270+// Underscore.js 1.5.2
4271+// http://underscorejs.org
4272+// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
4273+// Underscore may be freely distributed under the MIT license.
4274+
4275+(function() {
4276+
4277+ // Baseline setup
4278+ // --------------
4279+
4280+ // Establish the root object, `window` in the browser, or `exports` on the server.
4281+ var root = this;
4282+
4283+ // Save the previous value of the `_` variable.
4284+ var previousUnderscore = root._;
4285+
4286+ // Establish the object that gets returned to break out of a loop iteration.
4287+ var breaker = {};
4288+
4289+ // Save bytes in the minified (but not gzipped) version:
4290+ var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
4291+
4292+ // Create quick reference variables for speed access to core prototypes.
4293+ var
4294+ push = ArrayProto.push,
4295+ slice = ArrayProto.slice,
4296+ concat = ArrayProto.concat,
4297+ toString = ObjProto.toString,
4298+ hasOwnProperty = ObjProto.hasOwnProperty;
4299+
4300+ // All **ECMAScript 5** native function implementations that we hope to use
4301+ // are declared here.
4302+ var
4303+ nativeForEach = ArrayProto.forEach,
4304+ nativeMap = ArrayProto.map,
4305+ nativeReduce = ArrayProto.reduce,
4306+ nativeReduceRight = ArrayProto.reduceRight,
4307+ nativeFilter = ArrayProto.filter,
4308+ nativeEvery = ArrayProto.every,
4309+ nativeSome = ArrayProto.some,
4310+ nativeIndexOf = ArrayProto.indexOf,
4311+ nativeLastIndexOf = ArrayProto.lastIndexOf,
4312+ nativeIsArray = Array.isArray,
4313+ nativeKeys = Object.keys,
4314+ nativeBind = FuncProto.bind;
4315+
4316+ // Create a safe reference to the Underscore object for use below.
4317+ var _ = function(obj) {
4318+ if (obj instanceof _) return obj;
4319+ if (!(this instanceof _)) return new _(obj);
4320+ this._wrapped = obj;
4321+ };
4322+
4323+ // Export the Underscore object for **Node.js**, with
4324+ // backwards-compatibility for the old `require()` API. If we're in
4325+ // the browser, add `_` as a global object via a string identifier,
4326+ // for Closure Compiler "advanced" mode.
4327+ if (typeof exports !== 'undefined') {
4328+ if (typeof module !== 'undefined' && module.exports) {
4329+ exports = module.exports = _;
4330+ }
4331+ exports._ = _;
4332+ } else {
4333+ root._ = _;
4334+ }
4335+
4336+ // Current version.
4337+ _.VERSION = '1.5.2';
4338+
4339+ // Collection Functions
4340+ // --------------------
4341+
4342+ // The cornerstone, an `each` implementation, aka `forEach`.
4343+ // Handles objects with the built-in `forEach`, arrays, and raw objects.
4344+ // Delegates to **ECMAScript 5**'s native `forEach` if available.
4345+ var each = _.each = _.forEach = function(obj, iterator, context) {
4346+ if (obj == null) return;
4347+ if (nativeForEach && obj.forEach === nativeForEach) {
4348+ obj.forEach(iterator, context);
4349+ } else if (obj.length === +obj.length) {
4350+ for (var i = 0, length = obj.length; i < length; i++) {
4351+ if (iterator.call(context, obj[i], i, obj) === breaker) return;
4352+ }
4353+ } else {
4354+ var keys = _.keys(obj);
4355+ for (var i = 0, length = keys.length; i < length; i++) {
4356+ if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
4357+ }
4358+ }
4359+ };
4360+
4361+ // Return the results of applying the iterator to each element.
4362+ // Delegates to **ECMAScript 5**'s native `map` if available.
4363+ _.map = _.collect = function(obj, iterator, context) {
4364+ var results = [];
4365+ if (obj == null) return results;
4366+ if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
4367+ each(obj, function(value, index, list) {
4368+ results.push(iterator.call(context, value, index, list));
4369+ });
4370+ return results;
4371+ };
4372+
4373+ var reduceError = 'Reduce of empty array with no initial value';
4374+
4375+ // **Reduce** builds up a single result from a list of values, aka `inject`,
4376+ // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
4377+ _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
4378+ var initial = arguments.length > 2;
4379+ if (obj == null) obj = [];
4380+ if (nativeReduce && obj.reduce === nativeReduce) {
4381+ if (context) iterator = _.bind(iterator, context);
4382+ return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
4383+ }
4384+ each(obj, function(value, index, list) {
4385+ if (!initial) {
4386+ memo = value;
4387+ initial = true;
4388+ } else {
4389+ memo = iterator.call(context, memo, value, index, list);
4390+ }
4391+ });
4392+ if (!initial) throw new TypeError(reduceError);
4393+ return memo;
4394+ };
4395+
4396+ // The right-associative version of reduce, also known as `foldr`.
4397+ // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
4398+ _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
4399+ var initial = arguments.length > 2;
4400+ if (obj == null) obj = [];
4401+ if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
4402+ if (context) iterator = _.bind(iterator, context);
4403+ return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
4404+ }
4405+ var length = obj.length;
4406+ if (length !== +length) {
4407+ var keys = _.keys(obj);
4408+ length = keys.length;
4409+ }
4410+ each(obj, function(value, index, list) {
4411+ index = keys ? keys[--length] : --length;
4412+ if (!initial) {
4413+ memo = obj[index];
4414+ initial = true;
4415+ } else {
4416+ memo = iterator.call(context, memo, obj[index], index, list);
4417+ }
4418+ });
4419+ if (!initial) throw new TypeError(reduceError);
4420+ return memo;
4421+ };
4422+
4423+ // Return the first value which passes a truth test. Aliased as `detect`.
4424+ _.find = _.detect = function(obj, iterator, context) {
4425+ var result;
4426+ any(obj, function(value, index, list) {
4427+ if (iterator.call(context, value, index, list)) {
4428+ result = value;
4429+ return true;
4430+ }
4431+ });
4432+ return result;
4433+ };
4434+
4435+ // Return all the elements that pass a truth test.
4436+ // Delegates to **ECMAScript 5**'s native `filter` if available.
4437+ // Aliased as `select`.
4438+ _.filter = _.select = function(obj, iterator, context) {
4439+ var results = [];
4440+ if (obj == null) return results;
4441+ if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
4442+ each(obj, function(value, index, list) {
4443+ if (iterator.call(context, value, index, list)) results.push(value);
4444+ });
4445+ return results;
4446+ };
4447+
4448+ // Return all the elements for which a truth test fails.
4449+ _.reject = function(obj, iterator, context) {
4450+ return _.filter(obj, function(value, index, list) {
4451+ return !iterator.call(context, value, index, list);
4452+ }, context);
4453+ };
4454+
4455+ // Determine whether all of the elements match a truth test.
4456+ // Delegates to **ECMAScript 5**'s native `every` if available.
4457+ // Aliased as `all`.
4458+ _.every = _.all = function(obj, iterator, context) {
4459+ iterator || (iterator = _.identity);
4460+ var result = true;
4461+ if (obj == null) return result;
4462+ if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
4463+ each(obj, function(value, index, list) {
4464+ if (!(result = result && iterator.call(context, value, index, list))) return breaker;
4465+ });
4466+ return !!result;
4467+ };
4468+
4469+ // Determine if at least one element in the object matches a truth test.
4470+ // Delegates to **ECMAScript 5**'s native `some` if available.
4471+ // Aliased as `any`.
4472+ var any = _.some = _.any = function(obj, iterator, context) {
4473+ iterator || (iterator = _.identity);
4474+ var result = false;
4475+ if (obj == null) return result;
4476+ if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
4477+ each(obj, function(value, index, list) {
4478+ if (result || (result = iterator.call(context, value, index, list))) return breaker;
4479+ });
4480+ return !!result;
4481+ };
4482+
4483+ // Determine if the array or object contains a given value (using `===`).
4484+ // Aliased as `include`.
4485+ _.contains = _.include = function(obj, target) {
4486+ if (obj == null) return false;
4487+ if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
4488+ return any(obj, function(value) {
4489+ return value === target;
4490+ });
4491+ };
4492+
4493+ // Invoke a method (with arguments) on every item in a collection.
4494+ _.invoke = function(obj, method) {
4495+ var args = slice.call(arguments, 2);
4496+ var isFunc = _.isFunction(method);
4497+ return _.map(obj, function(value) {
4498+ return (isFunc ? method : value[method]).apply(value, args);
4499+ });
4500+ };
4501+
4502+ // Convenience version of a common use case of `map`: fetching a property.
4503+ _.pluck = function(obj, key) {
4504+ return _.map(obj, function(value){ return value[key]; });
4505+ };
4506+
4507+ // Convenience version of a common use case of `filter`: selecting only objects
4508+ // containing specific `key:value` pairs.
4509+ _.where = function(obj, attrs, first) {
4510+ if (_.isEmpty(attrs)) return first ? void 0 : [];
4511+ return _[first ? 'find' : 'filter'](obj, function(value) {
4512+ for (var key in attrs) {
4513+ if (attrs[key] !== value[key]) return false;
4514+ }
4515+ return true;
4516+ });
4517+ };
4518+
4519+ // Convenience version of a common use case of `find`: getting the first object
4520+ // containing specific `key:value` pairs.
4521+ _.findWhere = function(obj, attrs) {
4522+ return _.where(obj, attrs, true);
4523+ };
4524+
4525+ // Return the maximum element or (element-based computation).
4526+ // Can't optimize arrays of integers longer than 65,535 elements.
4527+ // See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797)
4528+ _.max = function(obj, iterator, context) {
4529+ if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
4530+ return Math.max.apply(Math, obj);
4531+ }
4532+ if (!iterator && _.isEmpty(obj)) return -Infinity;
4533+ var result = {computed : -Infinity, value: -Infinity};
4534+ each(obj, function(value, index, list) {
4535+ var computed = iterator ? iterator.call(context, value, index, list) : value;
4536+ computed > result.computed && (result = {value : value, computed : computed});
4537+ });
4538+ return result.value;
4539+ };
4540+
4541+ // Return the minimum element (or element-based computation).
4542+ _.min = function(obj, iterator, context) {
4543+ if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
4544+ return Math.min.apply(Math, obj);
4545+ }
4546+ if (!iterator && _.isEmpty(obj)) return Infinity;
4547+ var result = {computed : Infinity, value: Infinity};
4548+ each(obj, function(value, index, list) {
4549+ var computed = iterator ? iterator.call(context, value, index, list) : value;
4550+ computed < result.computed && (result = {value : value, computed : computed});
4551+ });
4552+ return result.value;
4553+ };
4554+
4555+ // Shuffle an array, using the modern version of the
4556+ // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
4557+ _.shuffle = function(obj) {
4558+ var rand;
4559+ var index = 0;
4560+ var shuffled = [];
4561+ each(obj, function(value) {
4562+ rand = _.random(index++);
4563+ shuffled[index - 1] = shuffled[rand];
4564+ shuffled[rand] = value;
4565+ });
4566+ return shuffled;
4567+ };
4568+
4569+ // Sample **n** random values from an array.
4570+ // If **n** is not specified, returns a single random element from the array.
4571+ // The internal `guard` argument allows it to work with `map`.
4572+ _.sample = function(obj, n, guard) {
4573+ if (arguments.length < 2 || guard) {
4574+ return obj[_.random(obj.length - 1)];
4575+ }
4576+ return _.shuffle(obj).slice(0, Math.max(0, n));
4577+ };
4578+
4579+ // An internal function to generate lookup iterators.
4580+ var lookupIterator = function(value) {
4581+ return _.isFunction(value) ? value : function(obj){ return obj[value]; };
4582+ };
4583+
4584+ // Sort the object's values by a criterion produced by an iterator.
4585+ _.sortBy = function(obj, value, context) {
4586+ var iterator = lookupIterator(value);
4587+ return _.pluck(_.map(obj, function(value, index, list) {
4588+ return {
4589+ value: value,
4590+ index: index,
4591+ criteria: iterator.call(context, value, index, list)
4592+ };
4593+ }).sort(function(left, right) {
4594+ var a = left.criteria;
4595+ var b = right.criteria;
4596+ if (a !== b) {
4597+ if (a > b || a === void 0) return 1;
4598+ if (a < b || b === void 0) return -1;
4599+ }
4600+ return left.index - right.index;
4601+ }), 'value');
4602+ };
4603+
4604+ // An internal function used for aggregate "group by" operations.
4605+ var group = function(behavior) {
4606+ return function(obj, value, context) {
4607+ var result = {};
4608+ var iterator = value == null ? _.identity : lookupIterator(value);
4609+ each(obj, function(value, index) {
4610+ var key = iterator.call(context, value, index, obj);
4611+ behavior(result, key, value);
4612+ });
4613+ return result;
4614+ };
4615+ };
4616+
4617+ // Groups the object's values by a criterion. Pass either a string attribute
4618+ // to group by, or a function that returns the criterion.
4619+ _.groupBy = group(function(result, key, value) {
4620+ (_.has(result, key) ? result[key] : (result[key] = [])).push(value);
4621+ });
4622+
4623+ // Indexes the object's values by a criterion, similar to `groupBy`, but for
4624+ // when you know that your index values will be unique.
4625+ _.indexBy = group(function(result, key, value) {
4626+ result[key] = value;
4627+ });
4628+
4629+ // Counts instances of an object that group by a certain criterion. Pass
4630+ // either a string attribute to count by, or a function that returns the
4631+ // criterion.
4632+ _.countBy = group(function(result, key) {
4633+ _.has(result, key) ? result[key]++ : result[key] = 1;
4634+ });
4635+
4636+ // Use a comparator function to figure out the smallest index at which
4637+ // an object should be inserted so as to maintain order. Uses binary search.
4638+ _.sortedIndex = function(array, obj, iterator, context) {
4639+ iterator = iterator == null ? _.identity : lookupIterator(iterator);
4640+ var value = iterator.call(context, obj);
4641+ var low = 0, high = array.length;
4642+ while (low < high) {
4643+ var mid = (low + high) >>> 1;
4644+ iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
4645+ }
4646+ return low;
4647+ };
4648+
4649+ // Safely create a real, live array from anything iterable.
4650+ _.toArray = function(obj) {
4651+ if (!obj) return [];
4652+ if (_.isArray(obj)) return slice.call(obj);
4653+ if (obj.length === +obj.length) return _.map(obj, _.identity);
4654+ return _.values(obj);
4655+ };
4656+
4657+ // Return the number of elements in an object.
4658+ _.size = function(obj) {
4659+ if (obj == null) return 0;
4660+ return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
4661+ };
4662+
4663+ // Array Functions
4664+ // ---------------
4665+
4666+ // Get the first element of an array. Passing **n** will return the first N
4667+ // values in the array. Aliased as `head` and `take`. The **guard** check
4668+ // allows it to work with `_.map`.
4669+ _.first = _.head = _.take = function(array, n, guard) {
4670+ if (array == null) return void 0;
4671+ return (n == null) || guard ? array[0] : slice.call(array, 0, n);
4672+ };
4673+
4674+ // Returns everything but the last entry of the array. Especially useful on
4675+ // the arguments object. Passing **n** will return all the values in
4676+ // the array, excluding the last N. The **guard** check allows it to work with
4677+ // `_.map`.
4678+ _.initial = function(array, n, guard) {
4679+ return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
4680+ };
4681+
4682+ // Get the last element of an array. Passing **n** will return the last N
4683+ // values in the array. The **guard** check allows it to work with `_.map`.
4684+ _.last = function(array, n, guard) {
4685+ if (array == null) return void 0;
4686+ if ((n == null) || guard) {
4687+ return array[array.length - 1];
4688+ } else {
4689+ return slice.call(array, Math.max(array.length - n, 0));
4690+ }
4691+ };
4692+
4693+ // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
4694+ // Especially useful on the arguments object. Passing an **n** will return
4695+ // the rest N values in the array. The **guard**
4696+ // check allows it to work with `_.map`.
4697+ _.rest = _.tail = _.drop = function(array, n, guard) {
4698+ return slice.call(array, (n == null) || guard ? 1 : n);
4699+ };
4700+
4701+ // Trim out all falsy values from an array.
4702+ _.compact = function(array) {
4703+ return _.filter(array, _.identity);
4704+ };
4705+
4706+ // Internal implementation of a recursive `flatten` function.
4707+ var flatten = function(input, shallow, output) {
4708+ if (shallow && _.every(input, _.isArray)) {
4709+ return concat.apply(output, input);
4710+ }
4711+ each(input, function(value) {
4712+ if (_.isArray(value) || _.isArguments(value)) {
4713+ shallow ? push.apply(output, value) : flatten(value, shallow, output);
4714+ } else {
4715+ output.push(value);
4716+ }
4717+ });
4718+ return output;
4719+ };
4720+
4721+ // Flatten out an array, either recursively (by default), or just one level.
4722+ _.flatten = function(array, shallow) {
4723+ return flatten(array, shallow, []);
4724+ };
4725+
4726+ // Return a version of the array that does not contain the specified value(s).
4727+ _.without = function(array) {
4728+ return _.difference(array, slice.call(arguments, 1));
4729+ };
4730+
4731+ // Produce a duplicate-free version of the array. If the array has already
4732+ // been sorted, you have the option of using a faster algorithm.
4733+ // Aliased as `unique`.
4734+ _.uniq = _.unique = function(array, isSorted, iterator, context) {
4735+ if (_.isFunction(isSorted)) {
4736+ context = iterator;
4737+ iterator = isSorted;
4738+ isSorted = false;
4739+ }
4740+ var initial = iterator ? _.map(array, iterator, context) : array;
4741+ var results = [];
4742+ var seen = [];
4743+ each(initial, function(value, index) {
4744+ if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
4745+ seen.push(value);
4746+ results.push(array[index]);
4747+ }
4748+ });
4749+ return results;
4750+ };
4751+
4752+ // Produce an array that contains the union: each distinct element from all of
4753+ // the passed-in arrays.
4754+ _.union = function() {
4755+ return _.uniq(_.flatten(arguments, true));
4756+ };
4757+
4758+ // Produce an array that contains every item shared between all the
4759+ // passed-in arrays.
4760+ _.intersection = function(array) {
4761+ var rest = slice.call(arguments, 1);
4762+ return _.filter(_.uniq(array), function(item) {
4763+ return _.every(rest, function(other) {
4764+ return _.indexOf(other, item) >= 0;
4765+ });
4766+ });
4767+ };
4768+
4769+ // Take the difference between one array and a number of other arrays.
4770+ // Only the elements present in just the first array will remain.
4771+ _.difference = function(array) {
4772+ var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
4773+ return _.filter(array, function(value){ return !_.contains(rest, value); });
4774+ };
4775+
4776+ // Zip together multiple lists into a single array -- elements that share
4777+ // an index go together.
4778+ _.zip = function() {
4779+ var length = _.max(_.pluck(arguments, "length").concat(0));
4780+ var results = new Array(length);
4781+ for (var i = 0; i < length; i++) {
4782+ results[i] = _.pluck(arguments, '' + i);
4783+ }
4784+ return results;
4785+ };
4786+
4787+ // Converts lists into objects. Pass either a single array of `[key, value]`
4788+ // pairs, or two parallel arrays of the same length -- one of keys, and one of
4789+ // the corresponding values.
4790+ _.object = function(list, values) {
4791+ if (list == null) return {};
4792+ var result = {};
4793+ for (var i = 0, length = list.length; i < length; i++) {
4794+ if (values) {
4795+ result[list[i]] = values[i];
4796+ } else {
4797+ result[list[i][0]] = list[i][1];
4798+ }
4799+ }
4800+ return result;
4801+ };
4802+
4803+ // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
4804+ // we need this function. Return the position of the first occurrence of an
4805+ // item in an array, or -1 if the item is not included in the array.
4806+ // Delegates to **ECMAScript 5**'s native `indexOf` if available.
4807+ // If the array is large and already in sort order, pass `true`
4808+ // for **isSorted** to use binary search.
4809+ _.indexOf = function(array, item, isSorted) {
4810+ if (array == null) return -1;
4811+ var i = 0, length = array.length;
4812+ if (isSorted) {
4813+ if (typeof isSorted == 'number') {
4814+ i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted);
4815+ } else {
4816+ i = _.sortedIndex(array, item);
4817+ return array[i] === item ? i : -1;
4818+ }
4819+ }
4820+ if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
4821+ for (; i < length; i++) if (array[i] === item) return i;
4822+ return -1;
4823+ };
4824+
4825+ // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
4826+ _.lastIndexOf = function(array, item, from) {
4827+ if (array == null) return -1;
4828+ var hasIndex = from != null;
4829+ if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
4830+ return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
4831+ }
4832+ var i = (hasIndex ? from : array.length);
4833+ while (i--) if (array[i] === item) return i;
4834+ return -1;
4835+ };
4836+
4837+ // Generate an integer Array containing an arithmetic progression. A port of
4838+ // the native Python `range()` function. See
4839+ // [the Python documentation](http://docs.python.org/library/functions.html#range).
4840+ _.range = function(start, stop, step) {
4841+ if (arguments.length <= 1) {
4842+ stop = start || 0;
4843+ start = 0;
4844+ }
4845+ step = arguments[2] || 1;
4846+
4847+ var length = Math.max(Math.ceil((stop - start) / step), 0);
4848+ var idx = 0;
4849+ var range = new Array(length);
4850+
4851+ while(idx < length) {
4852+ range[idx++] = start;
4853+ start += step;
4854+ }
4855+
4856+ return range;
4857+ };
4858+
4859+ // Function (ahem) Functions
4860+ // ------------------
4861+
4862+ // Reusable constructor function for prototype setting.
4863+ var ctor = function(){};
4864+
4865+ // Create a function bound to a given object (assigning `this`, and arguments,
4866+ // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
4867+ // available.
4868+ _.bind = function(func, context) {
4869+ var args, bound;
4870+ if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
4871+ if (!_.isFunction(func)) throw new TypeError;
4872+ args = slice.call(arguments, 2);
4873+ return bound = function() {
4874+ if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
4875+ ctor.prototype = func.prototype;
4876+ var self = new ctor;
4877+ ctor.prototype = null;
4878+ var result = func.apply(self, args.concat(slice.call(arguments)));
4879+ if (Object(result) === result) return result;
4880+ return self;
4881+ };
4882+ };
4883+
4884+ // Partially apply a function by creating a version that has had some of its
4885+ // arguments pre-filled, without changing its dynamic `this` context.
4886+ _.partial = function(func) {
4887+ var args = slice.call(arguments, 1);
4888+ return function() {
4889+ return func.apply(this, args.concat(slice.call(arguments)));
4890+ };
4891+ };
4892+
4893+ // Bind all of an object's methods to that object. Useful for ensuring that
4894+ // all callbacks defined on an object belong to it.
4895+ _.bindAll = function(obj) {
4896+ var funcs = slice.call(arguments, 1);
4897+ if (funcs.length === 0) throw new Error("bindAll must be passed function names");
4898+ each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
4899+ return obj;
4900+ };
4901+
4902+ // Memoize an expensive function by storing its results.
4903+ _.memoize = function(func, hasher) {
4904+ var memo = {};
4905+ hasher || (hasher = _.identity);
4906+ return function() {
4907+ var key = hasher.apply(this, arguments);
4908+ return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
4909+ };
4910+ };
4911+
4912+ // Delays a function for the given number of milliseconds, and then calls
4913+ // it with the arguments supplied.
4914+ _.delay = function(func, wait) {
4915+ var args = slice.call(arguments, 2);
4916+ return setTimeout(function(){ return func.apply(null, args); }, wait);
4917+ };
4918+
4919+ // Defers a function, scheduling it to run after the current call stack has
4920+ // cleared.
4921+ _.defer = function(func) {
4922+ return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
4923+ };
4924+
4925+ // Returns a function, that, when invoked, will only be triggered at most once
4926+ // during a given window of time. Normally, the throttled function will run
4927+ // as much as it can, without ever going more than once per `wait` duration;
4928+ // but if you'd like to disable the execution on the leading edge, pass
4929+ // `{leading: false}`. To disable execution on the trailing edge, ditto.
4930+ _.throttle = function(func, wait, options) {
4931+ var context, args, result;
4932+ var timeout = null;
4933+ var previous = 0;
4934+ options || (options = {});
4935+ var later = function() {
4936+ previous = options.leading === false ? 0 : new Date;
4937+ timeout = null;
4938+ result = func.apply(context, args);
4939+ };
4940+ return function() {
4941+ var now = new Date;
4942+ if (!previous && options.leading === false) previous = now;
4943+ var remaining = wait - (now - previous);
4944+ context = this;
4945+ args = arguments;
4946+ if (remaining <= 0) {
4947+ clearTimeout(timeout);
4948+ timeout = null;
4949+ previous = now;
4950+ result = func.apply(context, args);
4951+ } else if (!timeout && options.trailing !== false) {
4952+ timeout = setTimeout(later, remaining);
4953+ }
4954+ return result;
4955+ };
4956+ };
4957+
4958+ // Returns a function, that, as long as it continues to be invoked, will not
4959+ // be triggered. The function will be called after it stops being called for
4960+ // N milliseconds. If `immediate` is passed, trigger the function on the
4961+ // leading edge, instead of the trailing.
4962+ _.debounce = function(func, wait, immediate) {
4963+ var timeout, args, context, timestamp, result;
4964+ return function() {
4965+ context = this;
4966+ args = arguments;
4967+ timestamp = new Date();
4968+ var later = function() {
4969+ var last = (new Date()) - timestamp;
4970+ if (last < wait) {
4971+ timeout = setTimeout(later, wait - last);
4972+ } else {
4973+ timeout = null;
4974+ if (!immediate) result = func.apply(context, args);
4975+ }
4976+ };
4977+ var callNow = immediate && !timeout;
4978+ if (!timeout) {
4979+ timeout = setTimeout(later, wait);
4980+ }
4981+ if (callNow) result = func.apply(context, args);
4982+ return result;
4983+ };
4984+ };
4985+
4986+ // Returns a function that will be executed at most one time, no matter how
4987+ // often you call it. Useful for lazy initialization.
4988+ _.once = function(func) {
4989+ var ran = false, memo;
4990+ return function() {
4991+ if (ran) return memo;
4992+ ran = true;
4993+ memo = func.apply(this, arguments);
4994+ func = null;
4995+ return memo;
4996+ };
4997+ };
4998+
4999+ // Returns the first function passed as an argument to the second,
5000+ // allowing you to adjust arguments, run code before and after, and
The diff has been truncated for viewing.

Subscribers

People subscribed via source and target branches