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