visualsearch-rails 0.0.1
Sign up to get free protection for your applications and to get access to all the features.
- data/.gitignore +7 -0
- data/.travis.yml +4 -0
- data/Changelog.md +4 -0
- data/Gemfile +2 -0
- data/Rakefile +5 -0
- data/Readme.md +24 -0
- data/app/assets/css/icons.css +19 -0
- data/app/assets/css/reset.css +30 -0
- data/app/assets/css/workspace.css +290 -0
- data/app/assets/images/cancel_search.png +0 -0
- data/app/assets/images/search_glyph.png +0 -0
- data/app/assets/javascripts/backbone-0.9.10.js +1498 -0
- data/app/assets/javascripts/dependencies.js +14843 -0
- data/app/assets/javascripts/jquery.ui.autocomplete.js +614 -0
- data/app/assets/javascripts/jquery.ui.core.js +324 -0
- data/app/assets/javascripts/jquery.ui.datepicker.js +5 -0
- data/app/assets/javascripts/jquery.ui.menu.js +621 -0
- data/app/assets/javascripts/jquery.ui.position.js +497 -0
- data/app/assets/javascripts/jquery.ui.widget.js +521 -0
- data/app/assets/javascripts/underscore-1.4.3.js +1221 -0
- data/app/assets/javascripts/visualsearch/js/models/search_facets.js +67 -0
- data/app/assets/javascripts/visualsearch/js/models/search_query.js +70 -0
- data/app/assets/javascripts/visualsearch/js/templates/search_box.jst +8 -0
- data/app/assets/javascripts/visualsearch/js/templates/search_facet.jst +9 -0
- data/app/assets/javascripts/visualsearch/js/templates/search_input.jst +1 -0
- data/app/assets/javascripts/visualsearch/js/templates/templates.js +7 -0
- data/app/assets/javascripts/visualsearch/js/utils/backbone_extensions.js +17 -0
- data/app/assets/javascripts/visualsearch/js/utils/hotkeys.js +99 -0
- data/app/assets/javascripts/visualsearch/js/utils/inflector.js +21 -0
- data/app/assets/javascripts/visualsearch/js/utils/jquery_extensions.js +197 -0
- data/app/assets/javascripts/visualsearch/js/utils/search_parser.js +87 -0
- data/app/assets/javascripts/visualsearch/js/views/search_box.js +447 -0
- data/app/assets/javascripts/visualsearch/js/views/search_facet.js +444 -0
- data/app/assets/javascripts/visualsearch/js/views/search_input.js +409 -0
- data/app/assets/javascripts/visualsearch/js/visualsearch.js +77 -0
- data/lib/generators/visual_search_install.rb +30 -0
- data/lib/visualsearch-rails.rb +2 -0
- data/lib/visualsearch/rails.rb +6 -0
- data/lib/visualsearch/version.rb +3 -0
- data/visualsearch-rails.gemspec +26 -0
- metadata +165 -0
data/.gitignore
ADDED
data/.travis.yml
ADDED
data/Changelog.md
ADDED
data/Gemfile
ADDED
data/Rakefile
ADDED
data/Readme.md
ADDED
@@ -0,0 +1,24 @@
|
|
1
|
+
# Visualsearch-Rails
|
2
|
+
[![Gem Version](https://badge.fury.io/rb/visualsearch-rails.png)](http://badge.fury.io/rb/visualsearch-rails)
|
3
|
+
|
4
|
+
A Ruby wrapper to integrate [VisualSearch](https://github.com/documentcloud/visualsearch) - A small library for enhancing ordinary search boxes with the ability to autocomplete faceted search queries.
|
5
|
+
|
6
|
+
## Installation
|
7
|
+
|
8
|
+
Add the gem to the Gemfile:
|
9
|
+
|
10
|
+
gem "visualsearch-rails"
|
11
|
+
|
12
|
+
## Usage
|
13
|
+
|
14
|
+
In your JavaScript manifest (e.g. `application.js`):
|
15
|
+
|
16
|
+
//= require visualsearch
|
17
|
+
|
18
|
+
|
19
|
+
## Licensing
|
20
|
+
|
21
|
+
|
22
|
+
The gem itself is released under the MIT license
|
23
|
+
|
24
|
+
:pray:
|
@@ -0,0 +1,19 @@
|
|
1
|
+
.VS-search .VS-icon {
|
2
|
+
background-repeat: no-repeat;
|
3
|
+
background-position: center center;
|
4
|
+
vertical-align: middle;
|
5
|
+
width: 16px; height: 16px;
|
6
|
+
}
|
7
|
+
.VS-search .VS-icon-cancel {
|
8
|
+
width: 11px; height: 11px;
|
9
|
+
background-position: center 0;
|
10
|
+
background-image: url('../assets/cancel_search.png');
|
11
|
+
cursor: pointer;
|
12
|
+
}
|
13
|
+
.VS-search .VS-icon-cancel:hover {
|
14
|
+
background-position: center -11px;
|
15
|
+
}
|
16
|
+
.VS-search .VS-icon-search {
|
17
|
+
width: 12px; height: 12px;
|
18
|
+
background-image: url('../assets/search_glyph.png');
|
19
|
+
}
|
@@ -0,0 +1,30 @@
|
|
1
|
+
/*------------------------------ RESET + DEFAULT STYLES ---------------------------------*/
|
2
|
+
|
3
|
+
/*
|
4
|
+
Eric Meyer's final reset.css
|
5
|
+
Source: http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/
|
6
|
+
*/
|
7
|
+
.VS-search div, .VS-search span, .VS-search a, .VS-search img,
|
8
|
+
.VS-search ul, .VS-search li, .VS-search form, .VS-search label,
|
9
|
+
.VS-interface ul, .VS-interface li, .VS-interface {
|
10
|
+
margin: 0;
|
11
|
+
padding: 0;
|
12
|
+
border: 0;
|
13
|
+
outline: 0;
|
14
|
+
font-weight: inherit;
|
15
|
+
font-style: inherit;
|
16
|
+
font-size: 100%;
|
17
|
+
font-family: inherit;
|
18
|
+
vertical-align: baseline;
|
19
|
+
}
|
20
|
+
|
21
|
+
.VS-search :focus {
|
22
|
+
outline: 0;
|
23
|
+
}
|
24
|
+
.VS-search {
|
25
|
+
line-height: 1;
|
26
|
+
color: black;
|
27
|
+
}
|
28
|
+
.VS-search ol, .VS-search ul {
|
29
|
+
list-style: none;
|
30
|
+
}
|
@@ -0,0 +1,290 @@
|
|
1
|
+
/* ===================== */
|
2
|
+
/* = General and Reset = */
|
3
|
+
/* ===================== */
|
4
|
+
|
5
|
+
.VS-search {
|
6
|
+
font-family: Arial, sans-serif;
|
7
|
+
color: #373737;
|
8
|
+
font-size: 12px;
|
9
|
+
}
|
10
|
+
.VS-search input {
|
11
|
+
display: block;
|
12
|
+
border: none;
|
13
|
+
-moz-box-shadow: none;
|
14
|
+
-webkit-box-shadow: none;
|
15
|
+
box-shadow: none;
|
16
|
+
outline: none;
|
17
|
+
margin: 0; padding: 4px;
|
18
|
+
background: transparent;
|
19
|
+
font-size: 16px;
|
20
|
+
line-height: 20px;
|
21
|
+
width: 100%;
|
22
|
+
}
|
23
|
+
.VS-interface, .VS-search .dialog, .VS-search input {
|
24
|
+
font-family: "Lucida Grande", "Lucida Sans Unicode", Helvetica, Arial, sans-serif !important;
|
25
|
+
line-height: 1.1em;
|
26
|
+
}
|
27
|
+
|
28
|
+
/* ========== */
|
29
|
+
/* = Layout = */
|
30
|
+
/* ========== */
|
31
|
+
|
32
|
+
.VS-search .VS-search-box {
|
33
|
+
cursor: text;
|
34
|
+
position: relative;
|
35
|
+
background: transparent;
|
36
|
+
border: 2px solid #ccc;
|
37
|
+
border-radius: 16px; -webkit-border-radius: 16px; -moz-border-radius: 16px;
|
38
|
+
background-color: #fafafa;
|
39
|
+
-webkit-box-shadow: inset 0px 0px 3px #ccc;
|
40
|
+
-moz-box-shadow: inset 0px 0px 3px #ccc;
|
41
|
+
box-shadow: inset 0px 0px 3px #ccc;
|
42
|
+
min-height: 28px;
|
43
|
+
height: auto;
|
44
|
+
}
|
45
|
+
.VS-search.VS-readonly .VS-search-box {
|
46
|
+
cursor: default;
|
47
|
+
}
|
48
|
+
.VS-search .VS-search-box.VS-focus {
|
49
|
+
border-color: #acf;
|
50
|
+
-webkit-box-shadow: inset 0px 0px 3px #acf;
|
51
|
+
-moz-box-shadow: inset 0px 0px 3px #acf;
|
52
|
+
box-shadow: inset 0px 0px 3px #acf;
|
53
|
+
}
|
54
|
+
.VS-search .VS-placeholder {
|
55
|
+
position: absolute;
|
56
|
+
top: 7px;
|
57
|
+
left: 4px;
|
58
|
+
margin: 0 20px 0 22px;
|
59
|
+
color: #808080;
|
60
|
+
font-size: 14px;
|
61
|
+
}
|
62
|
+
.VS-search .VS-search-box.VS-focus .VS-placeholder,
|
63
|
+
.VS-search .VS-search-box .VS-placeholder.VS-hidden {
|
64
|
+
display: none;
|
65
|
+
}
|
66
|
+
.VS-search .VS-search-inner {
|
67
|
+
position: relative;
|
68
|
+
margin: 0 20px 0 22px;
|
69
|
+
overflow: hidden;
|
70
|
+
}
|
71
|
+
.VS-search input {
|
72
|
+
width: 100px;
|
73
|
+
}
|
74
|
+
.VS-search input,
|
75
|
+
.VS-search .VS-input-width-tester {
|
76
|
+
padding: 6px 0;
|
77
|
+
float: left;
|
78
|
+
color: #808080;
|
79
|
+
font: 13px/17px Helvetica, Arial;
|
80
|
+
}
|
81
|
+
.VS-search.VS-focus input {
|
82
|
+
color: #606060;
|
83
|
+
}
|
84
|
+
.VS-search .VS-icon-search {
|
85
|
+
position: absolute;
|
86
|
+
left: 9px; top: 8px;
|
87
|
+
}
|
88
|
+
.VS-search .VS-icon-cancel {
|
89
|
+
position: absolute;
|
90
|
+
right: 9px; top: 8px;
|
91
|
+
}
|
92
|
+
.VS-search.VS-readonly .VS-icon-cancel {
|
93
|
+
display: none;
|
94
|
+
}
|
95
|
+
|
96
|
+
/* ================ */
|
97
|
+
/* = Search Facet = */
|
98
|
+
/* ================ */
|
99
|
+
|
100
|
+
.VS-search .search_facet {
|
101
|
+
float: left;
|
102
|
+
margin: 0;
|
103
|
+
padding: 0 0 0 14px;
|
104
|
+
position: relative;
|
105
|
+
border: 1px solid transparent;
|
106
|
+
height: 20px;
|
107
|
+
margin: 3px -3px 3px 0;
|
108
|
+
}
|
109
|
+
.VS-search.VS-readonly .search_facet {
|
110
|
+
padding-left: 0;
|
111
|
+
}
|
112
|
+
.VS-search .search_facet.is_selected {
|
113
|
+
margin-left: -3px;
|
114
|
+
-webkit-border-radius: 16px;
|
115
|
+
-moz-border-radius: 16px;
|
116
|
+
border-radius: 16px;
|
117
|
+
background-color: #d2e6fd;
|
118
|
+
background-image: -moz-linear-gradient(top, #d2e6fd, #b0d1f9); /* FF3.6 */
|
119
|
+
background-image: -webkit-gradient(linear, left top, left bottom, from(#d2e6fd), to(#b0d1f9)); /* Saf4+, Chrome */
|
120
|
+
background-image: linear-gradient(top, #d2e6fd, #b0d1f9);
|
121
|
+
border: 1px solid #6eadf5;
|
122
|
+
}
|
123
|
+
.VS-search .search_facet .category {
|
124
|
+
float: left;
|
125
|
+
text-transform: uppercase;
|
126
|
+
font-weight: bold;
|
127
|
+
font-size: 10px;
|
128
|
+
color: #808080;
|
129
|
+
padding: 8px 0 5px;
|
130
|
+
line-height: 13px;
|
131
|
+
cursor: pointer;
|
132
|
+
padding: 4px 0 0;
|
133
|
+
}
|
134
|
+
.VS-search.VS-readonly .search_facet .category {
|
135
|
+
cursor: default;
|
136
|
+
}
|
137
|
+
.VS-search .search_facet.is_selected .category {
|
138
|
+
margin-left: 3px;
|
139
|
+
}
|
140
|
+
.VS-search .search_facet .search_facet_input_container {
|
141
|
+
float: left;
|
142
|
+
}
|
143
|
+
.VS-search .search_facet input {
|
144
|
+
margin: 0;
|
145
|
+
padding: 0;
|
146
|
+
color: #000;
|
147
|
+
font-size: 13px;
|
148
|
+
line-height: 16px;
|
149
|
+
padding: 5px 0 5px 4px;
|
150
|
+
height: 16px;
|
151
|
+
width: auto;
|
152
|
+
z-index: 100;
|
153
|
+
position: relative;
|
154
|
+
padding-top: 1px;
|
155
|
+
padding-bottom: 2px;
|
156
|
+
padding-right: 3px;
|
157
|
+
|
158
|
+
}
|
159
|
+
.VS-search .search_facet.is_editing input,
|
160
|
+
.VS-search .search_facet.is_selected input {
|
161
|
+
color: #000;
|
162
|
+
}
|
163
|
+
.VS-search.VS-readonly .search_facet .search_facet_remove {
|
164
|
+
display: none;
|
165
|
+
}
|
166
|
+
.VS-search .search_facet .search_facet_remove {
|
167
|
+
position: absolute;
|
168
|
+
left: 0;
|
169
|
+
top: 4px;
|
170
|
+
}
|
171
|
+
.VS-search .search_facet.is_selected .search_facet_remove {
|
172
|
+
opacity: 0.4;
|
173
|
+
left: 3px;
|
174
|
+
filter: alpha(opacity=40);
|
175
|
+
background-position: center -11px;
|
176
|
+
}
|
177
|
+
.VS-search .search_facet .search_facet_remove:hover {
|
178
|
+
opacity: 1;
|
179
|
+
}
|
180
|
+
.VS-search .search_facet.is_editing .category,
|
181
|
+
.VS-search .search_facet.is_selected .category {
|
182
|
+
color: #000;
|
183
|
+
}
|
184
|
+
.VS-search .search_facet.search_facet_maybe_delete .category,
|
185
|
+
.VS-search .search_facet.search_facet_maybe_delete input {
|
186
|
+
color: darkred;
|
187
|
+
}
|
188
|
+
|
189
|
+
/* ================ */
|
190
|
+
/* = Search Input = */
|
191
|
+
/* ================ */
|
192
|
+
|
193
|
+
.VS-search .search_input {
|
194
|
+
height: 28px;
|
195
|
+
float: left;
|
196
|
+
margin-left: -1px;
|
197
|
+
}
|
198
|
+
.VS-search .search_input input {
|
199
|
+
padding: 6px 3px 6px 2px;
|
200
|
+
line-height: 10px;
|
201
|
+
height: 22px;
|
202
|
+
margin-top: -4px;
|
203
|
+
width: 10px;
|
204
|
+
z-index: 100;
|
205
|
+
min-width: 4px;
|
206
|
+
position: relative;
|
207
|
+
}
|
208
|
+
.VS-search .search_input.is_editing input {
|
209
|
+
color: #202020;
|
210
|
+
}
|
211
|
+
|
212
|
+
/* ================ */
|
213
|
+
/* = Autocomplete = */
|
214
|
+
/* ================ */
|
215
|
+
|
216
|
+
.ui-helper-hidden-accessible {
|
217
|
+
display: none;
|
218
|
+
}
|
219
|
+
|
220
|
+
.VS-interface.ui-autocomplete {
|
221
|
+
position: absolute;
|
222
|
+
border: 1px solid #C0C0C0;
|
223
|
+
border-top: 1px solid #D9D9D9;
|
224
|
+
background-color: #F6F6F6;
|
225
|
+
cursor: pointer;
|
226
|
+
z-index: 10000;
|
227
|
+
padding: 0;
|
228
|
+
margin: 0;
|
229
|
+
width: auto;
|
230
|
+
min-width: 80px;
|
231
|
+
max-width: 220px;
|
232
|
+
max-height: 240px;
|
233
|
+
overflow-y: auto;
|
234
|
+
overflow-x: hidden;
|
235
|
+
font-size: 13px;
|
236
|
+
top: 5px;
|
237
|
+
opacity: 0.97;
|
238
|
+
box-shadow: 3px 4px 5px -2px rgba(0, 0, 0, 0.5); -webkit-box-shadow: 3px 4px 5px -2px rgba(0, 0, 0, 0.5); -moz-box-shadow: 3px 4px 5px -2px rgba(0, 0, 0, 0.5);
|
239
|
+
}
|
240
|
+
.VS-interface.ui-autocomplete .ui-autocomplete-category {
|
241
|
+
text-transform: capitalize;
|
242
|
+
font-size: 11px;
|
243
|
+
padding: 4px 4px 4px;
|
244
|
+
border-top: 1px solid #A2A2A2;
|
245
|
+
border-bottom: 1px solid #A2A2A2;
|
246
|
+
background-color: #B7B7B7;
|
247
|
+
text-shadow: 0 -1px 0 #999;
|
248
|
+
font-weight: bold;
|
249
|
+
color: white;
|
250
|
+
cursor: default;
|
251
|
+
}
|
252
|
+
.VS-interface.ui-autocomplete .ui-menu-item {
|
253
|
+
float: none;
|
254
|
+
}
|
255
|
+
.VS-interface.ui-autocomplete .ui-menu-item a {
|
256
|
+
color: #000;
|
257
|
+
outline: none;
|
258
|
+
display: block;
|
259
|
+
padding: 3px 4px 5px;
|
260
|
+
border-radius: none;
|
261
|
+
line-height: 1;
|
262
|
+
background-color: #F8F8F8;
|
263
|
+
background-image: -moz-linear-gradient(top, #F8F8F8, #F3F3F3); /* FF3.6 */
|
264
|
+
background-image: -webkit-gradient(linear, left top, left bottom, from(#F8F8F8), to(#F3F3F3)); /* Saf4+, Chrome */
|
265
|
+
background-image: linear-gradient(top, #F8F8F8, #F3F3F3);
|
266
|
+
border-top: 1px solid #FAFAFA;
|
267
|
+
border-bottom: 1px solid #f0f0f0;
|
268
|
+
}
|
269
|
+
.VS-interface.ui-autocomplete .ui-menu-item a:active {
|
270
|
+
outline: none;
|
271
|
+
}
|
272
|
+
.VS-interface.ui-autocomplete .ui-menu-item .ui-state-hover, .VS-interface.ui-autocomplete .ui-menu-item .ui-state-focus {
|
273
|
+
background-color: #6483F7;
|
274
|
+
background-image: -moz-linear-gradient(top, #648bF5, #2465f3); /* FF3.6 */
|
275
|
+
background-image: -webkit-gradient(linear, left top, left bottom, from(#648bF5), to(#2465f3)); /* Saf4+, Chrome */
|
276
|
+
background-image: linear-gradient(top, #648bF5, #2465f3);
|
277
|
+
border-top: 1px solid #5b83ec;
|
278
|
+
border-bottom: 1px solid #1459e9;
|
279
|
+
border-left: none;
|
280
|
+
border-right: none;
|
281
|
+
color: white;
|
282
|
+
margin: 0;
|
283
|
+
}
|
284
|
+
.VS-interface.ui-autocomplete .ui-corner-all {
|
285
|
+
border-radius: 0;
|
286
|
+
}
|
287
|
+
.VS-interface.ui-autocomplete li {
|
288
|
+
list-style: none;
|
289
|
+
width: auto;
|
290
|
+
}
|
Binary file
|
Binary file
|
@@ -0,0 +1,1498 @@
|
|
1
|
+
// Backbone.js 0.9.10
|
2
|
+
|
3
|
+
// (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc.
|
4
|
+
// Backbone may be freely distributed under the MIT license.
|
5
|
+
// For all details and documentation:
|
6
|
+
// http://backbonejs.org
|
7
|
+
|
8
|
+
(function(){
|
9
|
+
|
10
|
+
// Initial Setup
|
11
|
+
// -------------
|
12
|
+
|
13
|
+
// Save a reference to the global object (`window` in the browser, `exports`
|
14
|
+
// on the server).
|
15
|
+
var root = this;
|
16
|
+
|
17
|
+
// Save the previous value of the `Backbone` variable, so that it can be
|
18
|
+
// restored later on, if `noConflict` is used.
|
19
|
+
var previousBackbone = root.Backbone;
|
20
|
+
|
21
|
+
// Create a local reference to array methods.
|
22
|
+
var array = [];
|
23
|
+
var push = array.push;
|
24
|
+
var slice = array.slice;
|
25
|
+
var splice = array.splice;
|
26
|
+
|
27
|
+
// The top-level namespace. All public Backbone classes and modules will
|
28
|
+
// be attached to this. Exported for both CommonJS and the browser.
|
29
|
+
var Backbone;
|
30
|
+
if (typeof exports !== 'undefined') {
|
31
|
+
Backbone = exports;
|
32
|
+
} else {
|
33
|
+
Backbone = root.Backbone = {};
|
34
|
+
}
|
35
|
+
|
36
|
+
// Current version of the library. Keep in sync with `package.json`.
|
37
|
+
Backbone.VERSION = '0.9.10';
|
38
|
+
|
39
|
+
// Require Underscore, if we're on the server, and it's not already present.
|
40
|
+
var _ = root._;
|
41
|
+
if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
|
42
|
+
|
43
|
+
// For Backbone's purposes, jQuery, Zepto, or Ender owns the `$` variable.
|
44
|
+
Backbone.$ = root.jQuery || root.Zepto || root.ender;
|
45
|
+
|
46
|
+
// Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
|
47
|
+
// to its previous owner. Returns a reference to this Backbone object.
|
48
|
+
Backbone.noConflict = function() {
|
49
|
+
root.Backbone = previousBackbone;
|
50
|
+
return this;
|
51
|
+
};
|
52
|
+
|
53
|
+
// Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
|
54
|
+
// will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and
|
55
|
+
// set a `X-Http-Method-Override` header.
|
56
|
+
Backbone.emulateHTTP = false;
|
57
|
+
|
58
|
+
// Turn on `emulateJSON` to support legacy servers that can't deal with direct
|
59
|
+
// `application/json` requests ... will encode the body as
|
60
|
+
// `application/x-www-form-urlencoded` instead and will send the model in a
|
61
|
+
// form param named `model`.
|
62
|
+
Backbone.emulateJSON = false;
|
63
|
+
|
64
|
+
// Backbone.Events
|
65
|
+
// ---------------
|
66
|
+
|
67
|
+
// Regular expression used to split event strings.
|
68
|
+
var eventSplitter = /\s+/;
|
69
|
+
|
70
|
+
// Implement fancy features of the Events API such as multiple event
|
71
|
+
// names `"change blur"` and jQuery-style event maps `{change: action}`
|
72
|
+
// in terms of the existing API.
|
73
|
+
var eventsApi = function(obj, action, name, rest) {
|
74
|
+
if (!name) return true;
|
75
|
+
if (typeof name === 'object') {
|
76
|
+
for (var key in name) {
|
77
|
+
obj[action].apply(obj, [key, name[key]].concat(rest));
|
78
|
+
}
|
79
|
+
} else if (eventSplitter.test(name)) {
|
80
|
+
var names = name.split(eventSplitter);
|
81
|
+
for (var i = 0, l = names.length; i < l; i++) {
|
82
|
+
obj[action].apply(obj, [names[i]].concat(rest));
|
83
|
+
}
|
84
|
+
} else {
|
85
|
+
return true;
|
86
|
+
}
|
87
|
+
};
|
88
|
+
|
89
|
+
// Optimized internal dispatch function for triggering events. Tries to
|
90
|
+
// keep the usual cases speedy (most Backbone events have 3 arguments).
|
91
|
+
var triggerEvents = function(events, args) {
|
92
|
+
var ev, i = -1, l = events.length;
|
93
|
+
switch (args.length) {
|
94
|
+
case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx);
|
95
|
+
return;
|
96
|
+
case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0]);
|
97
|
+
return;
|
98
|
+
case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0], args[1]);
|
99
|
+
return;
|
100
|
+
case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0], args[1], args[2]);
|
101
|
+
return;
|
102
|
+
default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
|
103
|
+
}
|
104
|
+
};
|
105
|
+
|
106
|
+
// A module that can be mixed in to *any object* in order to provide it with
|
107
|
+
// custom events. You may bind with `on` or remove with `off` callback
|
108
|
+
// functions to an event; `trigger`-ing an event fires all callbacks in
|
109
|
+
// succession.
|
110
|
+
//
|
111
|
+
// var object = {};
|
112
|
+
// _.extend(object, Backbone.Events);
|
113
|
+
// object.on('expand', function(){ alert('expanded'); });
|
114
|
+
// object.trigger('expand');
|
115
|
+
//
|
116
|
+
var Events = Backbone.Events = {
|
117
|
+
|
118
|
+
// Bind one or more space separated events, or an events map,
|
119
|
+
// to a `callback` function. Passing `"all"` will bind the callback to
|
120
|
+
// all events fired.
|
121
|
+
on: function(name, callback, context) {
|
122
|
+
if (!(eventsApi(this, 'on', name, [callback, context]) && callback)) return this;
|
123
|
+
this._events || (this._events = {});
|
124
|
+
var list = this._events[name] || (this._events[name] = []);
|
125
|
+
list.push({callback: callback, context: context, ctx: context || this});
|
126
|
+
return this;
|
127
|
+
},
|
128
|
+
|
129
|
+
// Bind events to only be triggered a single time. After the first time
|
130
|
+
// the callback is invoked, it will be removed.
|
131
|
+
once: function(name, callback, context) {
|
132
|
+
if (!(eventsApi(this, 'once', name, [callback, context]) && callback)) return this;
|
133
|
+
var self = this;
|
134
|
+
var once = _.once(function() {
|
135
|
+
self.off(name, once);
|
136
|
+
callback.apply(this, arguments);
|
137
|
+
});
|
138
|
+
once._callback = callback;
|
139
|
+
this.on(name, once, context);
|
140
|
+
return this;
|
141
|
+
},
|
142
|
+
|
143
|
+
// Remove one or many callbacks. If `context` is null, removes all
|
144
|
+
// callbacks with that function. If `callback` is null, removes all
|
145
|
+
// callbacks for the event. If `name` is null, removes all bound
|
146
|
+
// callbacks for all events.
|
147
|
+
off: function(name, callback, context) {
|
148
|
+
var list, ev, events, names, i, l, j, k;
|
149
|
+
if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
|
150
|
+
if (!name && !callback && !context) {
|
151
|
+
this._events = {};
|
152
|
+
return this;
|
153
|
+
}
|
154
|
+
|
155
|
+
names = name ? [name] : _.keys(this._events);
|
156
|
+
for (i = 0, l = names.length; i < l; i++) {
|
157
|
+
name = names[i];
|
158
|
+
if (list = this._events[name]) {
|
159
|
+
events = [];
|
160
|
+
if (callback || context) {
|
161
|
+
for (j = 0, k = list.length; j < k; j++) {
|
162
|
+
ev = list[j];
|
163
|
+
if ((callback && callback !== ev.callback &&
|
164
|
+
callback !== ev.callback._callback) ||
|
165
|
+
(context && context !== ev.context)) {
|
166
|
+
events.push(ev);
|
167
|
+
}
|
168
|
+
}
|
169
|
+
}
|
170
|
+
this._events[name] = events;
|
171
|
+
}
|
172
|
+
}
|
173
|
+
|
174
|
+
return this;
|
175
|
+
},
|
176
|
+
|
177
|
+
// Trigger one or many events, firing all bound callbacks. Callbacks are
|
178
|
+
// passed the same arguments as `trigger` is, apart from the event name
|
179
|
+
// (unless you're listening on `"all"`, which will cause your callback to
|
180
|
+
// receive the true name of the event as the first argument).
|
181
|
+
trigger: function(name) {
|
182
|
+
if (!this._events) return this;
|
183
|
+
var args = slice.call(arguments, 1);
|
184
|
+
if (!eventsApi(this, 'trigger', name, args)) return this;
|
185
|
+
var events = this._events[name];
|
186
|
+
var allEvents = this._events.all;
|
187
|
+
if (events) triggerEvents(events, args);
|
188
|
+
if (allEvents) triggerEvents(allEvents, arguments);
|
189
|
+
return this;
|
190
|
+
},
|
191
|
+
|
192
|
+
// An inversion-of-control version of `on`. Tell *this* object to listen to
|
193
|
+
// an event in another object ... keeping track of what it's listening to.
|
194
|
+
listenTo: function(obj, name, callback) {
|
195
|
+
var listeners = this._listeners || (this._listeners = {});
|
196
|
+
var id = obj._listenerId || (obj._listenerId = _.uniqueId('l'));
|
197
|
+
listeners[id] = obj;
|
198
|
+
obj.on(name, typeof name === 'object' ? this : callback, this);
|
199
|
+
return this;
|
200
|
+
},
|
201
|
+
|
202
|
+
// Tell this object to stop listening to either specific events ... or
|
203
|
+
// to every object it's currently listening to.
|
204
|
+
stopListening: function(obj, name, callback) {
|
205
|
+
var listeners = this._listeners;
|
206
|
+
if (!listeners) return;
|
207
|
+
if (obj) {
|
208
|
+
obj.off(name, typeof name === 'object' ? this : callback, this);
|
209
|
+
if (!name && !callback) delete listeners[obj._listenerId];
|
210
|
+
} else {
|
211
|
+
if (typeof name === 'object') callback = this;
|
212
|
+
for (var id in listeners) {
|
213
|
+
listeners[id].off(name, callback, this);
|
214
|
+
}
|
215
|
+
this._listeners = {};
|
216
|
+
}
|
217
|
+
return this;
|
218
|
+
}
|
219
|
+
};
|
220
|
+
|
221
|
+
// Aliases for backwards compatibility.
|
222
|
+
Events.bind = Events.on;
|
223
|
+
Events.unbind = Events.off;
|
224
|
+
|
225
|
+
// Allow the `Backbone` object to serve as a global event bus, for folks who
|
226
|
+
// want global "pubsub" in a convenient place.
|
227
|
+
_.extend(Backbone, Events);
|
228
|
+
|
229
|
+
// Backbone.Model
|
230
|
+
// --------------
|
231
|
+
|
232
|
+
// Create a new model, with defined attributes. A client id (`cid`)
|
233
|
+
// is automatically generated and assigned for you.
|
234
|
+
var Model = Backbone.Model = function(attributes, options) {
|
235
|
+
var defaults;
|
236
|
+
var attrs = attributes || {};
|
237
|
+
this.cid = _.uniqueId('c');
|
238
|
+
this.attributes = {};
|
239
|
+
if (options && options.collection) this.collection = options.collection;
|
240
|
+
if (options && options.parse) attrs = this.parse(attrs, options) || {};
|
241
|
+
if (defaults = _.result(this, 'defaults')) {
|
242
|
+
attrs = _.defaults({}, attrs, defaults);
|
243
|
+
}
|
244
|
+
this.set(attrs, options);
|
245
|
+
this.changed = {};
|
246
|
+
this.initialize.apply(this, arguments);
|
247
|
+
};
|
248
|
+
|
249
|
+
// Attach all inheritable methods to the Model prototype.
|
250
|
+
_.extend(Model.prototype, Events, {
|
251
|
+
|
252
|
+
// A hash of attributes whose current and previous value differ.
|
253
|
+
changed: null,
|
254
|
+
|
255
|
+
// The default name for the JSON `id` attribute is `"id"`. MongoDB and
|
256
|
+
// CouchDB users may want to set this to `"_id"`.
|
257
|
+
idAttribute: 'id',
|
258
|
+
|
259
|
+
// Initialize is an empty function by default. Override it with your own
|
260
|
+
// initialization logic.
|
261
|
+
initialize: function(){},
|
262
|
+
|
263
|
+
// Return a copy of the model's `attributes` object.
|
264
|
+
toJSON: function(options) {
|
265
|
+
return _.clone(this.attributes);
|
266
|
+
},
|
267
|
+
|
268
|
+
// Proxy `Backbone.sync` by default.
|
269
|
+
sync: function() {
|
270
|
+
return Backbone.sync.apply(this, arguments);
|
271
|
+
},
|
272
|
+
|
273
|
+
// Get the value of an attribute.
|
274
|
+
get: function(attr) {
|
275
|
+
return this.attributes[attr];
|
276
|
+
},
|
277
|
+
|
278
|
+
// Get the HTML-escaped value of an attribute.
|
279
|
+
escape: function(attr) {
|
280
|
+
return _.escape(this.get(attr));
|
281
|
+
},
|
282
|
+
|
283
|
+
// Returns `true` if the attribute contains a value that is not null
|
284
|
+
// or undefined.
|
285
|
+
has: function(attr) {
|
286
|
+
return this.get(attr) != null;
|
287
|
+
},
|
288
|
+
|
289
|
+
// ----------------------------------------------------------------------
|
290
|
+
|
291
|
+
// Set a hash of model attributes on the object, firing `"change"` unless
|
292
|
+
// you choose to silence it.
|
293
|
+
set: function(key, val, options) {
|
294
|
+
var attr, attrs, unset, changes, silent, changing, prev, current;
|
295
|
+
if (key == null) return this;
|
296
|
+
|
297
|
+
// Handle both `"key", value` and `{key: value}` -style arguments.
|
298
|
+
if (typeof key === 'object') {
|
299
|
+
attrs = key;
|
300
|
+
options = val;
|
301
|
+
} else {
|
302
|
+
(attrs = {})[key] = val;
|
303
|
+
}
|
304
|
+
|
305
|
+
options || (options = {});
|
306
|
+
|
307
|
+
// Run validation.
|
308
|
+
if (!this._validate(attrs, options)) return false;
|
309
|
+
|
310
|
+
// Extract attributes and options.
|
311
|
+
unset = options.unset;
|
312
|
+
silent = options.silent;
|
313
|
+
changes = [];
|
314
|
+
changing = this._changing;
|
315
|
+
this._changing = true;
|
316
|
+
|
317
|
+
if (!changing) {
|
318
|
+
this._previousAttributes = _.clone(this.attributes);
|
319
|
+
this.changed = {};
|
320
|
+
}
|
321
|
+
current = this.attributes, prev = this._previousAttributes;
|
322
|
+
|
323
|
+
// Check for changes of `id`.
|
324
|
+
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
|
325
|
+
|
326
|
+
// For each `set` attribute, update or delete the current value.
|
327
|
+
for (attr in attrs) {
|
328
|
+
val = attrs[attr];
|
329
|
+
if (!_.isEqual(current[attr], val)) changes.push(attr);
|
330
|
+
if (!_.isEqual(prev[attr], val)) {
|
331
|
+
this.changed[attr] = val;
|
332
|
+
} else {
|
333
|
+
delete this.changed[attr];
|
334
|
+
}
|
335
|
+
unset ? delete current[attr] : current[attr] = val;
|
336
|
+
}
|
337
|
+
|
338
|
+
// Trigger all relevant attribute changes.
|
339
|
+
if (!silent) {
|
340
|
+
if (changes.length) this._pending = true;
|
341
|
+
for (var i = 0, l = changes.length; i < l; i++) {
|
342
|
+
this.trigger('change:' + changes[i], this, current[changes[i]], options);
|
343
|
+
}
|
344
|
+
}
|
345
|
+
|
346
|
+
if (changing) return this;
|
347
|
+
if (!silent) {
|
348
|
+
while (this._pending) {
|
349
|
+
this._pending = false;
|
350
|
+
this.trigger('change', this, options);
|
351
|
+
}
|
352
|
+
}
|
353
|
+
this._pending = false;
|
354
|
+
this._changing = false;
|
355
|
+
return this;
|
356
|
+
},
|
357
|
+
|
358
|
+
// Remove an attribute from the model, firing `"change"` unless you choose
|
359
|
+
// to silence it. `unset` is a noop if the attribute doesn't exist.
|
360
|
+
unset: function(attr, options) {
|
361
|
+
return this.set(attr, void 0, _.extend({}, options, {unset: true}));
|
362
|
+
},
|
363
|
+
|
364
|
+
// Clear all attributes on the model, firing `"change"` unless you choose
|
365
|
+
// to silence it.
|
366
|
+
clear: function(options) {
|
367
|
+
var attrs = {};
|
368
|
+
for (var key in this.attributes) attrs[key] = void 0;
|
369
|
+
return this.set(attrs, _.extend({}, options, {unset: true}));
|
370
|
+
},
|
371
|
+
|
372
|
+
// Determine if the model has changed since the last `"change"` event.
|
373
|
+
// If you specify an attribute name, determine if that attribute has changed.
|
374
|
+
hasChanged: function(attr) {
|
375
|
+
if (attr == null) return !_.isEmpty(this.changed);
|
376
|
+
return _.has(this.changed, attr);
|
377
|
+
},
|
378
|
+
|
379
|
+
// Return an object containing all the attributes that have changed, or
|
380
|
+
// false if there are no changed attributes. Useful for determining what
|
381
|
+
// parts of a view need to be updated and/or what attributes need to be
|
382
|
+
// persisted to the server. Unset attributes will be set to undefined.
|
383
|
+
// You can also pass an attributes object to diff against the model,
|
384
|
+
// determining if there *would be* a change.
|
385
|
+
changedAttributes: function(diff) {
|
386
|
+
if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
|
387
|
+
var val, changed = false;
|
388
|
+
var old = this._changing ? this._previousAttributes : this.attributes;
|
389
|
+
for (var attr in diff) {
|
390
|
+
if (_.isEqual(old[attr], (val = diff[attr]))) continue;
|
391
|
+
(changed || (changed = {}))[attr] = val;
|
392
|
+
}
|
393
|
+
return changed;
|
394
|
+
},
|
395
|
+
|
396
|
+
// Get the previous value of an attribute, recorded at the time the last
|
397
|
+
// `"change"` event was fired.
|
398
|
+
previous: function(attr) {
|
399
|
+
if (attr == null || !this._previousAttributes) return null;
|
400
|
+
return this._previousAttributes[attr];
|
401
|
+
},
|
402
|
+
|
403
|
+
// Get all of the attributes of the model at the time of the previous
|
404
|
+
// `"change"` event.
|
405
|
+
previousAttributes: function() {
|
406
|
+
return _.clone(this._previousAttributes);
|
407
|
+
},
|
408
|
+
|
409
|
+
// ---------------------------------------------------------------------
|
410
|
+
|
411
|
+
// Fetch the model from the server. If the server's representation of the
|
412
|
+
// model differs from its current attributes, they will be overriden,
|
413
|
+
// triggering a `"change"` event.
|
414
|
+
fetch: function(options) {
|
415
|
+
options = options ? _.clone(options) : {};
|
416
|
+
if (options.parse === void 0) options.parse = true;
|
417
|
+
var success = options.success;
|
418
|
+
options.success = function(model, resp, options) {
|
419
|
+
if (!model.set(model.parse(resp, options), options)) return false;
|
420
|
+
if (success) success(model, resp, options);
|
421
|
+
};
|
422
|
+
return this.sync('read', this, options);
|
423
|
+
},
|
424
|
+
|
425
|
+
// Set a hash of model attributes, and sync the model to the server.
|
426
|
+
// If the server returns an attributes hash that differs, the model's
|
427
|
+
// state will be `set` again.
|
428
|
+
save: function(key, val, options) {
|
429
|
+
var attrs, success, method, xhr, attributes = this.attributes;
|
430
|
+
|
431
|
+
// Handle both `"key", value` and `{key: value}` -style arguments.
|
432
|
+
if (key == null || typeof key === 'object') {
|
433
|
+
attrs = key;
|
434
|
+
options = val;
|
435
|
+
} else {
|
436
|
+
(attrs = {})[key] = val;
|
437
|
+
}
|
438
|
+
|
439
|
+
// If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`.
|
440
|
+
if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false;
|
441
|
+
|
442
|
+
options = _.extend({validate: true}, options);
|
443
|
+
|
444
|
+
// Do not persist invalid models.
|
445
|
+
if (!this._validate(attrs, options)) return false;
|
446
|
+
|
447
|
+
// Set temporary attributes if `{wait: true}`.
|
448
|
+
if (attrs && options.wait) {
|
449
|
+
this.attributes = _.extend({}, attributes, attrs);
|
450
|
+
}
|
451
|
+
|
452
|
+
// After a successful server-side save, the client is (optionally)
|
453
|
+
// updated with the server-side state.
|
454
|
+
if (options.parse === void 0) options.parse = true;
|
455
|
+
success = options.success;
|
456
|
+
options.success = function(model, resp, options) {
|
457
|
+
// Ensure attributes are restored during synchronous saves.
|
458
|
+
model.attributes = attributes;
|
459
|
+
var serverAttrs = model.parse(resp, options);
|
460
|
+
if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
|
461
|
+
if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
|
462
|
+
return false;
|
463
|
+
}
|
464
|
+
if (success) success(model, resp, options);
|
465
|
+
};
|
466
|
+
|
467
|
+
// Finish configuring and sending the Ajax request.
|
468
|
+
method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
|
469
|
+
if (method === 'patch') options.attrs = attrs;
|
470
|
+
xhr = this.sync(method, this, options);
|
471
|
+
|
472
|
+
// Restore attributes.
|
473
|
+
if (attrs && options.wait) this.attributes = attributes;
|
474
|
+
|
475
|
+
return xhr;
|
476
|
+
},
|
477
|
+
|
478
|
+
// Destroy this model on the server if it was already persisted.
|
479
|
+
// Optimistically removes the model from its collection, if it has one.
|
480
|
+
// If `wait: true` is passed, waits for the server to respond before removal.
|
481
|
+
destroy: function(options) {
|
482
|
+
options = options ? _.clone(options) : {};
|
483
|
+
var model = this;
|
484
|
+
var success = options.success;
|
485
|
+
|
486
|
+
var destroy = function() {
|
487
|
+
model.trigger('destroy', model, model.collection, options);
|
488
|
+
};
|
489
|
+
|
490
|
+
options.success = function(model, resp, options) {
|
491
|
+
if (options.wait || model.isNew()) destroy();
|
492
|
+
if (success) success(model, resp, options);
|
493
|
+
};
|
494
|
+
|
495
|
+
if (this.isNew()) {
|
496
|
+
options.success(this, null, options);
|
497
|
+
return false;
|
498
|
+
}
|
499
|
+
|
500
|
+
var xhr = this.sync('delete', this, options);
|
501
|
+
if (!options.wait) destroy();
|
502
|
+
return xhr;
|
503
|
+
},
|
504
|
+
|
505
|
+
// Default URL for the model's representation on the server -- if you're
|
506
|
+
// using Backbone's restful methods, override this to change the endpoint
|
507
|
+
// that will be called.
|
508
|
+
url: function() {
|
509
|
+
var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
|
510
|
+
if (this.isNew()) return base;
|
511
|
+
return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
|
512
|
+
},
|
513
|
+
|
514
|
+
// **parse** converts a response into the hash of attributes to be `set` on
|
515
|
+
// the model. The default implementation is just to pass the response along.
|
516
|
+
parse: function(resp, options) {
|
517
|
+
return resp;
|
518
|
+
},
|
519
|
+
|
520
|
+
// Create a new model with identical attributes to this one.
|
521
|
+
clone: function() {
|
522
|
+
return new this.constructor(this.attributes);
|
523
|
+
},
|
524
|
+
|
525
|
+
// A model is new if it has never been saved to the server, and lacks an id.
|
526
|
+
isNew: function() {
|
527
|
+
return this.id == null;
|
528
|
+
},
|
529
|
+
|
530
|
+
// Check if the model is currently in a valid state.
|
531
|
+
isValid: function(options) {
|
532
|
+
return !this.validate || !this.validate(this.attributes, options);
|
533
|
+
},
|
534
|
+
|
535
|
+
// Run validation against the next complete set of model attributes,
|
536
|
+
// returning `true` if all is well. Otherwise, fire a general
|
537
|
+
// `"error"` event and call the error callback, if specified.
|
538
|
+
_validate: function(attrs, options) {
|
539
|
+
if (!options.validate || !this.validate) return true;
|
540
|
+
attrs = _.extend({}, this.attributes, attrs);
|
541
|
+
var error = this.validationError = this.validate(attrs, options) || null;
|
542
|
+
if (!error) return true;
|
543
|
+
this.trigger('invalid', this, error, options || {});
|
544
|
+
return false;
|
545
|
+
}
|
546
|
+
|
547
|
+
});
|
548
|
+
|
549
|
+
// Backbone.Collection
|
550
|
+
// -------------------
|
551
|
+
|
552
|
+
// Provides a standard collection class for our sets of models, ordered
|
553
|
+
// or unordered. If a `comparator` is specified, the Collection will maintain
|
554
|
+
// its models in sort order, as they're added and removed.
|
555
|
+
var Collection = Backbone.Collection = function(models, options) {
|
556
|
+
options || (options = {});
|
557
|
+
if (options.model) this.model = options.model;
|
558
|
+
if (options.comparator !== void 0) this.comparator = options.comparator;
|
559
|
+
this.models = [];
|
560
|
+
this._reset();
|
561
|
+
this.initialize.apply(this, arguments);
|
562
|
+
if (models) this.reset(models, _.extend({silent: true}, options));
|
563
|
+
};
|
564
|
+
|
565
|
+
// Define the Collection's inheritable methods.
|
566
|
+
_.extend(Collection.prototype, Events, {
|
567
|
+
|
568
|
+
// The default model for a collection is just a **Backbone.Model**.
|
569
|
+
// This should be overridden in most cases.
|
570
|
+
model: Model,
|
571
|
+
|
572
|
+
// Initialize is an empty function by default. Override it with your own
|
573
|
+
// initialization logic.
|
574
|
+
initialize: function(){},
|
575
|
+
|
576
|
+
// The JSON representation of a Collection is an array of the
|
577
|
+
// models' attributes.
|
578
|
+
toJSON: function(options) {
|
579
|
+
return this.map(function(model){ return model.toJSON(options); });
|
580
|
+
},
|
581
|
+
|
582
|
+
// Proxy `Backbone.sync` by default.
|
583
|
+
sync: function() {
|
584
|
+
return Backbone.sync.apply(this, arguments);
|
585
|
+
},
|
586
|
+
|
587
|
+
// Add a model, or list of models to the set.
|
588
|
+
add: function(models, options) {
|
589
|
+
models = _.isArray(models) ? models.slice() : [models];
|
590
|
+
options || (options = {});
|
591
|
+
var i, l, model, attrs, existing, doSort, add, at, sort, sortAttr;
|
592
|
+
add = [];
|
593
|
+
at = options.at;
|
594
|
+
sort = this.comparator && (at == null) && options.sort != false;
|
595
|
+
sortAttr = _.isString(this.comparator) ? this.comparator : null;
|
596
|
+
|
597
|
+
// Turn bare objects into model references, and prevent invalid models
|
598
|
+
// from being added.
|
599
|
+
for (i = 0, l = models.length; i < l; i++) {
|
600
|
+
if (!(model = this._prepareModel(attrs = models[i], options))) {
|
601
|
+
this.trigger('invalid', this, attrs, options);
|
602
|
+
continue;
|
603
|
+
}
|
604
|
+
|
605
|
+
// If a duplicate is found, prevent it from being added and
|
606
|
+
// optionally merge it into the existing model.
|
607
|
+
if (existing = this.get(model)) {
|
608
|
+
if (options.merge) {
|
609
|
+
existing.set(attrs === model ? model.attributes : attrs, options);
|
610
|
+
if (sort && !doSort && existing.hasChanged(sortAttr)) doSort = true;
|
611
|
+
}
|
612
|
+
continue;
|
613
|
+
}
|
614
|
+
|
615
|
+
// This is a new model, push it to the `add` list.
|
616
|
+
add.push(model);
|
617
|
+
|
618
|
+
// Listen to added models' events, and index models for lookup by
|
619
|
+
// `id` and by `cid`.
|
620
|
+
model.on('all', this._onModelEvent, this);
|
621
|
+
this._byId[model.cid] = model;
|
622
|
+
if (model.id != null) this._byId[model.id] = model;
|
623
|
+
}
|
624
|
+
|
625
|
+
// See if sorting is needed, update `length` and splice in new models.
|
626
|
+
if (add.length) {
|
627
|
+
if (sort) doSort = true;
|
628
|
+
this.length += add.length;
|
629
|
+
if (at != null) {
|
630
|
+
splice.apply(this.models, [at, 0].concat(add));
|
631
|
+
} else {
|
632
|
+
push.apply(this.models, add);
|
633
|
+
}
|
634
|
+
}
|
635
|
+
|
636
|
+
// Silently sort the collection if appropriate.
|
637
|
+
if (doSort) this.sort({silent: true});
|
638
|
+
|
639
|
+
if (options.silent) return this;
|
640
|
+
|
641
|
+
// Trigger `add` events.
|
642
|
+
for (i = 0, l = add.length; i < l; i++) {
|
643
|
+
(model = add[i]).trigger('add', model, this, options);
|
644
|
+
}
|
645
|
+
|
646
|
+
// Trigger `sort` if the collection was sorted.
|
647
|
+
if (doSort) this.trigger('sort', this, options);
|
648
|
+
|
649
|
+
return this;
|
650
|
+
},
|
651
|
+
|
652
|
+
// Remove a model, or a list of models from the set.
|
653
|
+
remove: function(models, options) {
|
654
|
+
models = _.isArray(models) ? models.slice() : [models];
|
655
|
+
options || (options = {});
|
656
|
+
var i, l, index, model;
|
657
|
+
for (i = 0, l = models.length; i < l; i++) {
|
658
|
+
model = this.get(models[i]);
|
659
|
+
if (!model) continue;
|
660
|
+
delete this._byId[model.id];
|
661
|
+
delete this._byId[model.cid];
|
662
|
+
index = this.indexOf(model);
|
663
|
+
this.models.splice(index, 1);
|
664
|
+
this.length--;
|
665
|
+
if (!options.silent) {
|
666
|
+
options.index = index;
|
667
|
+
model.trigger('remove', model, this, options);
|
668
|
+
}
|
669
|
+
this._removeReference(model);
|
670
|
+
}
|
671
|
+
return this;
|
672
|
+
},
|
673
|
+
|
674
|
+
// Add a model to the end of the collection.
|
675
|
+
push: function(model, options) {
|
676
|
+
model = this._prepareModel(model, options);
|
677
|
+
this.add(model, _.extend({at: this.length}, options));
|
678
|
+
return model;
|
679
|
+
},
|
680
|
+
|
681
|
+
// Remove a model from the end of the collection.
|
682
|
+
pop: function(options) {
|
683
|
+
var model = this.at(this.length - 1);
|
684
|
+
this.remove(model, options);
|
685
|
+
return model;
|
686
|
+
},
|
687
|
+
|
688
|
+
// Add a model to the beginning of the collection.
|
689
|
+
unshift: function(model, options) {
|
690
|
+
model = this._prepareModel(model, options);
|
691
|
+
this.add(model, _.extend({at: 0}, options));
|
692
|
+
return model;
|
693
|
+
},
|
694
|
+
|
695
|
+
// Remove a model from the beginning of the collection.
|
696
|
+
shift: function(options) {
|
697
|
+
var model = this.at(0);
|
698
|
+
this.remove(model, options);
|
699
|
+
return model;
|
700
|
+
},
|
701
|
+
|
702
|
+
// Slice out a sub-array of models from the collection.
|
703
|
+
slice: function(begin, end) {
|
704
|
+
return this.models.slice(begin, end);
|
705
|
+
},
|
706
|
+
|
707
|
+
// Get a model from the set by id.
|
708
|
+
get: function(obj) {
|
709
|
+
if (obj == null) return void 0;
|
710
|
+
this._idAttr || (this._idAttr = this.model.prototype.idAttribute);
|
711
|
+
return this._byId[obj.id || obj.cid || obj[this._idAttr] || obj];
|
712
|
+
},
|
713
|
+
|
714
|
+
// Get the model at the given index.
|
715
|
+
at: function(index) {
|
716
|
+
return this.models[index];
|
717
|
+
},
|
718
|
+
|
719
|
+
// Return models with matching attributes. Useful for simple cases of `filter`.
|
720
|
+
where: function(attrs) {
|
721
|
+
if (_.isEmpty(attrs)) return [];
|
722
|
+
return this.filter(function(model) {
|
723
|
+
for (var key in attrs) {
|
724
|
+
if (attrs[key] !== model.get(key)) return false;
|
725
|
+
}
|
726
|
+
return true;
|
727
|
+
});
|
728
|
+
},
|
729
|
+
|
730
|
+
// Force the collection to re-sort itself. You don't need to call this under
|
731
|
+
// normal circumstances, as the set will maintain sort order as each item
|
732
|
+
// is added.
|
733
|
+
sort: function(options) {
|
734
|
+
if (!this.comparator) {
|
735
|
+
throw new Error('Cannot sort a set without a comparator');
|
736
|
+
}
|
737
|
+
options || (options = {});
|
738
|
+
|
739
|
+
// Run sort based on type of `comparator`.
|
740
|
+
if (_.isString(this.comparator) || this.comparator.length === 1) {
|
741
|
+
this.models = this.sortBy(this.comparator, this);
|
742
|
+
} else {
|
743
|
+
this.models.sort(_.bind(this.comparator, this));
|
744
|
+
}
|
745
|
+
|
746
|
+
if (!options.silent) this.trigger('sort', this, options);
|
747
|
+
return this;
|
748
|
+
},
|
749
|
+
|
750
|
+
// Pluck an attribute from each model in the collection.
|
751
|
+
pluck: function(attr) {
|
752
|
+
return _.invoke(this.models, 'get', attr);
|
753
|
+
},
|
754
|
+
|
755
|
+
// Smartly update a collection with a change set of models, adding,
|
756
|
+
// removing, and merging as necessary.
|
757
|
+
update: function(models, options) {
|
758
|
+
options = _.extend({add: true, merge: true, remove: true}, options);
|
759
|
+
if (options.parse) models = this.parse(models, options);
|
760
|
+
var model, i, l, existing;
|
761
|
+
var add = [], remove = [], modelMap = {};
|
762
|
+
|
763
|
+
// Allow a single model (or no argument) to be passed.
|
764
|
+
if (!_.isArray(models)) models = models ? [models] : [];
|
765
|
+
|
766
|
+
// Proxy to `add` for this case, no need to iterate...
|
767
|
+
if (options.add && !options.remove) return this.add(models, options);
|
768
|
+
|
769
|
+
// Determine which models to add and merge, and which to remove.
|
770
|
+
for (i = 0, l = models.length; i < l; i++) {
|
771
|
+
model = models[i];
|
772
|
+
existing = this.get(model);
|
773
|
+
if (options.remove && existing) modelMap[existing.cid] = true;
|
774
|
+
if ((options.add && !existing) || (options.merge && existing)) {
|
775
|
+
add.push(model);
|
776
|
+
}
|
777
|
+
}
|
778
|
+
if (options.remove) {
|
779
|
+
for (i = 0, l = this.models.length; i < l; i++) {
|
780
|
+
model = this.models[i];
|
781
|
+
if (!modelMap[model.cid]) remove.push(model);
|
782
|
+
}
|
783
|
+
}
|
784
|
+
|
785
|
+
// Remove models (if applicable) before we add and merge the rest.
|
786
|
+
if (remove.length) this.remove(remove, options);
|
787
|
+
if (add.length) this.add(add, options);
|
788
|
+
return this;
|
789
|
+
},
|
790
|
+
|
791
|
+
// When you have more items than you want to add or remove individually,
|
792
|
+
// you can reset the entire set with a new list of models, without firing
|
793
|
+
// any `add` or `remove` events. Fires `reset` when finished.
|
794
|
+
reset: function(models, options) {
|
795
|
+
options || (options = {});
|
796
|
+
if (options.parse) models = this.parse(models, options);
|
797
|
+
for (var i = 0, l = this.models.length; i < l; i++) {
|
798
|
+
this._removeReference(this.models[i]);
|
799
|
+
}
|
800
|
+
options.previousModels = this.models.slice();
|
801
|
+
this._reset();
|
802
|
+
if (models) this.add(models, _.extend({silent: true}, options));
|
803
|
+
if (!options.silent) this.trigger('reset', this, options);
|
804
|
+
return this;
|
805
|
+
},
|
806
|
+
|
807
|
+
// Fetch the default set of models for this collection, resetting the
|
808
|
+
// collection when they arrive. If `update: true` is passed, the response
|
809
|
+
// data will be passed through the `update` method instead of `reset`.
|
810
|
+
fetch: function(options) {
|
811
|
+
options = options ? _.clone(options) : {};
|
812
|
+
if (options.parse === void 0) options.parse = true;
|
813
|
+
var success = options.success;
|
814
|
+
options.success = function(collection, resp, options) {
|
815
|
+
var method = options.update ? 'update' : 'reset';
|
816
|
+
collection[method](resp, options);
|
817
|
+
if (success) success(collection, resp, options);
|
818
|
+
};
|
819
|
+
return this.sync('read', this, options);
|
820
|
+
},
|
821
|
+
|
822
|
+
// Create a new instance of a model in this collection. Add the model to the
|
823
|
+
// collection immediately, unless `wait: true` is passed, in which case we
|
824
|
+
// wait for the server to agree.
|
825
|
+
create: function(model, options) {
|
826
|
+
options = options ? _.clone(options) : {};
|
827
|
+
if (!(model = this._prepareModel(model, options))) return false;
|
828
|
+
if (!options.wait) this.add(model, options);
|
829
|
+
var collection = this;
|
830
|
+
var success = options.success;
|
831
|
+
options.success = function(model, resp, options) {
|
832
|
+
if (options.wait) collection.add(model, options);
|
833
|
+
if (success) success(model, resp, options);
|
834
|
+
};
|
835
|
+
model.save(null, options);
|
836
|
+
return model;
|
837
|
+
},
|
838
|
+
|
839
|
+
// **parse** converts a response into a list of models to be added to the
|
840
|
+
// collection. The default implementation is just to pass it through.
|
841
|
+
parse: function(resp, options) {
|
842
|
+
return resp;
|
843
|
+
},
|
844
|
+
|
845
|
+
// Create a new collection with an identical list of models as this one.
|
846
|
+
clone: function() {
|
847
|
+
return new this.constructor(this.models);
|
848
|
+
},
|
849
|
+
|
850
|
+
// Reset all internal state. Called when the collection is reset.
|
851
|
+
_reset: function() {
|
852
|
+
this.length = 0;
|
853
|
+
this.models.length = 0;
|
854
|
+
this._byId = {};
|
855
|
+
},
|
856
|
+
|
857
|
+
// Prepare a model or hash of attributes to be added to this collection.
|
858
|
+
_prepareModel: function(attrs, options) {
|
859
|
+
if (attrs instanceof Model) {
|
860
|
+
if (!attrs.collection) attrs.collection = this;
|
861
|
+
return attrs;
|
862
|
+
}
|
863
|
+
options || (options = {});
|
864
|
+
options.collection = this;
|
865
|
+
var model = new this.model(attrs, options);
|
866
|
+
if (!model._validate(attrs, options)) return false;
|
867
|
+
return model;
|
868
|
+
},
|
869
|
+
|
870
|
+
// Internal method to remove a model's ties to a collection.
|
871
|
+
_removeReference: function(model) {
|
872
|
+
if (this === model.collection) delete model.collection;
|
873
|
+
model.off('all', this._onModelEvent, this);
|
874
|
+
},
|
875
|
+
|
876
|
+
// Internal method called every time a model in the set fires an event.
|
877
|
+
// Sets need to update their indexes when models change ids. All other
|
878
|
+
// events simply proxy through. "add" and "remove" events that originate
|
879
|
+
// in other collections are ignored.
|
880
|
+
_onModelEvent: function(event, model, collection, options) {
|
881
|
+
if ((event === 'add' || event === 'remove') && collection !== this) return;
|
882
|
+
if (event === 'destroy') this.remove(model, options);
|
883
|
+
if (model && event === 'change:' + model.idAttribute) {
|
884
|
+
delete this._byId[model.previous(model.idAttribute)];
|
885
|
+
if (model.id != null) this._byId[model.id] = model;
|
886
|
+
}
|
887
|
+
this.trigger.apply(this, arguments);
|
888
|
+
},
|
889
|
+
|
890
|
+
sortedIndex: function (model, value, context) {
|
891
|
+
value || (value = this.comparator);
|
892
|
+
var iterator = _.isFunction(value) ? value : function(model) {
|
893
|
+
return model.get(value);
|
894
|
+
};
|
895
|
+
return _.sortedIndex(this.models, model, iterator, context);
|
896
|
+
}
|
897
|
+
|
898
|
+
});
|
899
|
+
|
900
|
+
// Underscore methods that we want to implement on the Collection.
|
901
|
+
var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
|
902
|
+
'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
|
903
|
+
'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
|
904
|
+
'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
|
905
|
+
'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf',
|
906
|
+
'isEmpty', 'chain'];
|
907
|
+
|
908
|
+
// Mix in each Underscore method as a proxy to `Collection#models`.
|
909
|
+
_.each(methods, function(method) {
|
910
|
+
Collection.prototype[method] = function() {
|
911
|
+
var args = slice.call(arguments);
|
912
|
+
args.unshift(this.models);
|
913
|
+
return _[method].apply(_, args);
|
914
|
+
};
|
915
|
+
});
|
916
|
+
|
917
|
+
// Underscore methods that take a property name as an argument.
|
918
|
+
var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
|
919
|
+
|
920
|
+
// Use attributes instead of properties.
|
921
|
+
_.each(attributeMethods, function(method) {
|
922
|
+
Collection.prototype[method] = function(value, context) {
|
923
|
+
var iterator = _.isFunction(value) ? value : function(model) {
|
924
|
+
return model.get(value);
|
925
|
+
};
|
926
|
+
return _[method](this.models, iterator, context);
|
927
|
+
};
|
928
|
+
});
|
929
|
+
|
930
|
+
// Backbone.Router
|
931
|
+
// ---------------
|
932
|
+
|
933
|
+
// Routers map faux-URLs to actions, and fire events when routes are
|
934
|
+
// matched. Creating a new one sets its `routes` hash, if not set statically.
|
935
|
+
var Router = Backbone.Router = function(options) {
|
936
|
+
options || (options = {});
|
937
|
+
if (options.routes) this.routes = options.routes;
|
938
|
+
this._bindRoutes();
|
939
|
+
this.initialize.apply(this, arguments);
|
940
|
+
};
|
941
|
+
|
942
|
+
// Cached regular expressions for matching named param parts and splatted
|
943
|
+
// parts of route strings.
|
944
|
+
var optionalParam = /\((.*?)\)/g;
|
945
|
+
var namedParam = /(\(\?)?:\w+/g;
|
946
|
+
var splatParam = /\*\w+/g;
|
947
|
+
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
|
948
|
+
|
949
|
+
// Set up all inheritable **Backbone.Router** properties and methods.
|
950
|
+
_.extend(Router.prototype, Events, {
|
951
|
+
|
952
|
+
// Initialize is an empty function by default. Override it with your own
|
953
|
+
// initialization logic.
|
954
|
+
initialize: function(){},
|
955
|
+
|
956
|
+
// Manually bind a single named route to a callback. For example:
|
957
|
+
//
|
958
|
+
// this.route('search/:query/p:num', 'search', function(query, num) {
|
959
|
+
// ...
|
960
|
+
// });
|
961
|
+
//
|
962
|
+
route: function(route, name, callback) {
|
963
|
+
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
|
964
|
+
if (!callback) callback = this[name];
|
965
|
+
Backbone.history.route(route, _.bind(function(fragment) {
|
966
|
+
var args = this._extractParameters(route, fragment);
|
967
|
+
callback && callback.apply(this, args);
|
968
|
+
this.trigger.apply(this, ['route:' + name].concat(args));
|
969
|
+
this.trigger('route', name, args);
|
970
|
+
Backbone.history.trigger('route', this, name, args);
|
971
|
+
}, this));
|
972
|
+
return this;
|
973
|
+
},
|
974
|
+
|
975
|
+
// Simple proxy to `Backbone.history` to save a fragment into the history.
|
976
|
+
navigate: function(fragment, options) {
|
977
|
+
Backbone.history.navigate(fragment, options);
|
978
|
+
return this;
|
979
|
+
},
|
980
|
+
|
981
|
+
// Bind all defined routes to `Backbone.history`. We have to reverse the
|
982
|
+
// order of the routes here to support behavior where the most general
|
983
|
+
// routes can be defined at the bottom of the route map.
|
984
|
+
_bindRoutes: function() {
|
985
|
+
if (!this.routes) return;
|
986
|
+
var route, routes = _.keys(this.routes);
|
987
|
+
while ((route = routes.pop()) != null) {
|
988
|
+
this.route(route, this.routes[route]);
|
989
|
+
}
|
990
|
+
},
|
991
|
+
|
992
|
+
// Convert a route string into a regular expression, suitable for matching
|
993
|
+
// against the current location hash.
|
994
|
+
_routeToRegExp: function(route) {
|
995
|
+
route = route.replace(escapeRegExp, '\\$&')
|
996
|
+
.replace(optionalParam, '(?:$1)?')
|
997
|
+
.replace(namedParam, function(match, optional){
|
998
|
+
return optional ? match : '([^\/]+)';
|
999
|
+
})
|
1000
|
+
.replace(splatParam, '(.*?)');
|
1001
|
+
return new RegExp('^' + route + '$');
|
1002
|
+
},
|
1003
|
+
|
1004
|
+
// Given a route, and a URL fragment that it matches, return the array of
|
1005
|
+
// extracted parameters.
|
1006
|
+
_extractParameters: function(route, fragment) {
|
1007
|
+
return route.exec(fragment).slice(1);
|
1008
|
+
}
|
1009
|
+
|
1010
|
+
});
|
1011
|
+
|
1012
|
+
// Backbone.History
|
1013
|
+
// ----------------
|
1014
|
+
|
1015
|
+
// Handles cross-browser history management, based on URL fragments. If the
|
1016
|
+
// browser does not support `onhashchange`, falls back to polling.
|
1017
|
+
var History = Backbone.History = function() {
|
1018
|
+
this.handlers = [];
|
1019
|
+
_.bindAll(this, 'checkUrl');
|
1020
|
+
|
1021
|
+
// Ensure that `History` can be used outside of the browser.
|
1022
|
+
if (typeof window !== 'undefined') {
|
1023
|
+
this.location = window.location;
|
1024
|
+
this.history = window.history;
|
1025
|
+
}
|
1026
|
+
};
|
1027
|
+
|
1028
|
+
// Cached regex for stripping a leading hash/slash and trailing space.
|
1029
|
+
var routeStripper = /^[#\/]|\s+$/g;
|
1030
|
+
|
1031
|
+
// Cached regex for stripping leading and trailing slashes.
|
1032
|
+
var rootStripper = /^\/+|\/+$/g;
|
1033
|
+
|
1034
|
+
// Cached regex for detecting MSIE.
|
1035
|
+
var isExplorer = /msie [\w.]+/;
|
1036
|
+
|
1037
|
+
// Cached regex for removing a trailing slash.
|
1038
|
+
var trailingSlash = /\/$/;
|
1039
|
+
|
1040
|
+
// Has the history handling already been started?
|
1041
|
+
History.started = false;
|
1042
|
+
|
1043
|
+
// Set up all inheritable **Backbone.History** properties and methods.
|
1044
|
+
_.extend(History.prototype, Events, {
|
1045
|
+
|
1046
|
+
// The default interval to poll for hash changes, if necessary, is
|
1047
|
+
// twenty times a second.
|
1048
|
+
interval: 50,
|
1049
|
+
|
1050
|
+
// Gets the true hash value. Cannot use location.hash directly due to bug
|
1051
|
+
// in Firefox where location.hash will always be decoded.
|
1052
|
+
getHash: function(window) {
|
1053
|
+
var match = (window || this).location.href.match(/#(.*)$/);
|
1054
|
+
return match ? match[1] : '';
|
1055
|
+
},
|
1056
|
+
|
1057
|
+
// Get the cross-browser normalized URL fragment, either from the URL,
|
1058
|
+
// the hash, or the override.
|
1059
|
+
getFragment: function(fragment, forcePushState) {
|
1060
|
+
if (fragment == null) {
|
1061
|
+
if (this._hasPushState || !this._wantsHashChange || forcePushState) {
|
1062
|
+
fragment = this.location.pathname;
|
1063
|
+
var root = this.root.replace(trailingSlash, '');
|
1064
|
+
if (!fragment.indexOf(root)) fragment = fragment.substr(root.length);
|
1065
|
+
} else {
|
1066
|
+
fragment = this.getHash();
|
1067
|
+
}
|
1068
|
+
}
|
1069
|
+
return fragment.replace(routeStripper, '');
|
1070
|
+
},
|
1071
|
+
|
1072
|
+
// Start the hash change handling, returning `true` if the current URL matches
|
1073
|
+
// an existing route, and `false` otherwise.
|
1074
|
+
start: function(options) {
|
1075
|
+
if (History.started) throw new Error("Backbone.history has already been started");
|
1076
|
+
History.started = true;
|
1077
|
+
|
1078
|
+
// Figure out the initial configuration. Do we need an iframe?
|
1079
|
+
// Is pushState desired ... is it available?
|
1080
|
+
this.options = _.extend({}, {root: '/'}, this.options, options);
|
1081
|
+
this.root = this.options.root;
|
1082
|
+
this._wantsHashChange = this.options.hashChange !== false;
|
1083
|
+
this._wantsPushState = !!this.options.pushState;
|
1084
|
+
this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
|
1085
|
+
var fragment = this.getFragment();
|
1086
|
+
var docMode = document.documentMode;
|
1087
|
+
var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
|
1088
|
+
|
1089
|
+
// Normalize root to always include a leading and trailing slash.
|
1090
|
+
this.root = ('/' + this.root + '/').replace(rootStripper, '/');
|
1091
|
+
|
1092
|
+
if (oldIE && this._wantsHashChange) {
|
1093
|
+
this.iframe = Backbone.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo('body')[0].contentWindow;
|
1094
|
+
this.navigate(fragment);
|
1095
|
+
}
|
1096
|
+
|
1097
|
+
// Depending on whether we're using pushState or hashes, and whether
|
1098
|
+
// 'onhashchange' is supported, determine how we check the URL state.
|
1099
|
+
if (this._hasPushState) {
|
1100
|
+
Backbone.$(window).on('popstate', this.checkUrl);
|
1101
|
+
} else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
|
1102
|
+
Backbone.$(window).on('hashchange', this.checkUrl);
|
1103
|
+
} else if (this._wantsHashChange) {
|
1104
|
+
this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
|
1105
|
+
}
|
1106
|
+
|
1107
|
+
// Determine if we need to change the base url, for a pushState link
|
1108
|
+
// opened by a non-pushState browser.
|
1109
|
+
this.fragment = fragment;
|
1110
|
+
var loc = this.location;
|
1111
|
+
var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
|
1112
|
+
|
1113
|
+
// If we've started off with a route from a `pushState`-enabled browser,
|
1114
|
+
// but we're currently in a browser that doesn't support it...
|
1115
|
+
if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
|
1116
|
+
this.fragment = this.getFragment(null, true);
|
1117
|
+
this.location.replace(this.root + this.location.search + '#' + this.fragment);
|
1118
|
+
// Return immediately as browser will do redirect to new url
|
1119
|
+
return true;
|
1120
|
+
|
1121
|
+
// Or if we've started out with a hash-based route, but we're currently
|
1122
|
+
// in a browser where it could be `pushState`-based instead...
|
1123
|
+
} else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
|
1124
|
+
this.fragment = this.getHash().replace(routeStripper, '');
|
1125
|
+
this.history.replaceState({}, document.title, this.root + this.fragment + loc.search);
|
1126
|
+
}
|
1127
|
+
|
1128
|
+
if (!this.options.silent) return this.loadUrl();
|
1129
|
+
},
|
1130
|
+
|
1131
|
+
// Disable Backbone.history, perhaps temporarily. Not useful in a real app,
|
1132
|
+
// but possibly useful for unit testing Routers.
|
1133
|
+
stop: function() {
|
1134
|
+
Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl);
|
1135
|
+
clearInterval(this._checkUrlInterval);
|
1136
|
+
History.started = false;
|
1137
|
+
},
|
1138
|
+
|
1139
|
+
// Add a route to be tested when the fragment changes. Routes added later
|
1140
|
+
// may override previous routes.
|
1141
|
+
route: function(route, callback) {
|
1142
|
+
this.handlers.unshift({route: route, callback: callback});
|
1143
|
+
},
|
1144
|
+
|
1145
|
+
// Checks the current URL to see if it has changed, and if it has,
|
1146
|
+
// calls `loadUrl`, normalizing across the hidden iframe.
|
1147
|
+
checkUrl: function(e) {
|
1148
|
+
var current = this.getFragment();
|
1149
|
+
if (current === this.fragment && this.iframe) {
|
1150
|
+
current = this.getFragment(this.getHash(this.iframe));
|
1151
|
+
}
|
1152
|
+
if (current === this.fragment) return false;
|
1153
|
+
if (this.iframe) this.navigate(current);
|
1154
|
+
this.loadUrl() || this.loadUrl(this.getHash());
|
1155
|
+
},
|
1156
|
+
|
1157
|
+
// Attempt to load the current URL fragment. If a route succeeds with a
|
1158
|
+
// match, returns `true`. If no defined routes matches the fragment,
|
1159
|
+
// returns `false`.
|
1160
|
+
loadUrl: function(fragmentOverride) {
|
1161
|
+
var fragment = this.fragment = this.getFragment(fragmentOverride);
|
1162
|
+
var matched = _.any(this.handlers, function(handler) {
|
1163
|
+
if (handler.route.test(fragment)) {
|
1164
|
+
handler.callback(fragment);
|
1165
|
+
return true;
|
1166
|
+
}
|
1167
|
+
});
|
1168
|
+
return matched;
|
1169
|
+
},
|
1170
|
+
|
1171
|
+
// Save a fragment into the hash history, or replace the URL state if the
|
1172
|
+
// 'replace' option is passed. You are responsible for properly URL-encoding
|
1173
|
+
// the fragment in advance.
|
1174
|
+
//
|
1175
|
+
// The options object can contain `trigger: true` if you wish to have the
|
1176
|
+
// route callback be fired (not usually desirable), or `replace: true`, if
|
1177
|
+
// you wish to modify the current URL without adding an entry to the history.
|
1178
|
+
navigate: function(fragment, options) {
|
1179
|
+
if (!History.started) return false;
|
1180
|
+
if (!options || options === true) options = {trigger: options};
|
1181
|
+
fragment = this.getFragment(fragment || '');
|
1182
|
+
if (this.fragment === fragment) return;
|
1183
|
+
this.fragment = fragment;
|
1184
|
+
var url = this.root + fragment;
|
1185
|
+
|
1186
|
+
// If pushState is available, we use it to set the fragment as a real URL.
|
1187
|
+
if (this._hasPushState) {
|
1188
|
+
this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
|
1189
|
+
|
1190
|
+
// If hash changes haven't been explicitly disabled, update the hash
|
1191
|
+
// fragment to store history.
|
1192
|
+
} else if (this._wantsHashChange) {
|
1193
|
+
this._updateHash(this.location, fragment, options.replace);
|
1194
|
+
if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) {
|
1195
|
+
// Opening and closing the iframe tricks IE7 and earlier to push a
|
1196
|
+
// history entry on hash-tag change. When replace is true, we don't
|
1197
|
+
// want this.
|
1198
|
+
if(!options.replace) this.iframe.document.open().close();
|
1199
|
+
this._updateHash(this.iframe.location, fragment, options.replace);
|
1200
|
+
}
|
1201
|
+
|
1202
|
+
// If you've told us that you explicitly don't want fallback hashchange-
|
1203
|
+
// based history, then `navigate` becomes a page refresh.
|
1204
|
+
} else {
|
1205
|
+
return this.location.assign(url);
|
1206
|
+
}
|
1207
|
+
if (options.trigger) this.loadUrl(fragment);
|
1208
|
+
},
|
1209
|
+
|
1210
|
+
// Update the hash location, either replacing the current entry, or adding
|
1211
|
+
// a new one to the browser history.
|
1212
|
+
_updateHash: function(location, fragment, replace) {
|
1213
|
+
if (replace) {
|
1214
|
+
var href = location.href.replace(/(javascript:|#).*$/, '');
|
1215
|
+
location.replace(href + '#' + fragment);
|
1216
|
+
} else {
|
1217
|
+
// Some browsers require that `hash` contains a leading #.
|
1218
|
+
location.hash = '#' + fragment;
|
1219
|
+
}
|
1220
|
+
}
|
1221
|
+
|
1222
|
+
});
|
1223
|
+
|
1224
|
+
// Create the default Backbone.history.
|
1225
|
+
Backbone.history = new History;
|
1226
|
+
|
1227
|
+
// Backbone.View
|
1228
|
+
// -------------
|
1229
|
+
|
1230
|
+
// Creating a Backbone.View creates its initial element outside of the DOM,
|
1231
|
+
// if an existing element is not provided...
|
1232
|
+
var View = Backbone.View = function(options) {
|
1233
|
+
this.cid = _.uniqueId('view');
|
1234
|
+
this._configure(options || {});
|
1235
|
+
this._ensureElement();
|
1236
|
+
this.initialize.apply(this, arguments);
|
1237
|
+
this.delegateEvents();
|
1238
|
+
};
|
1239
|
+
|
1240
|
+
// Cached regex to split keys for `delegate`.
|
1241
|
+
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
|
1242
|
+
|
1243
|
+
// List of view options to be merged as properties.
|
1244
|
+
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
|
1245
|
+
|
1246
|
+
// Set up all inheritable **Backbone.View** properties and methods.
|
1247
|
+
_.extend(View.prototype, Events, {
|
1248
|
+
|
1249
|
+
// The default `tagName` of a View's element is `"div"`.
|
1250
|
+
tagName: 'div',
|
1251
|
+
|
1252
|
+
// jQuery delegate for element lookup, scoped to DOM elements within the
|
1253
|
+
// current view. This should be prefered to global lookups where possible.
|
1254
|
+
$: function(selector) {
|
1255
|
+
return this.$el.find(selector);
|
1256
|
+
},
|
1257
|
+
|
1258
|
+
// Initialize is an empty function by default. Override it with your own
|
1259
|
+
// initialization logic.
|
1260
|
+
initialize: function(){},
|
1261
|
+
|
1262
|
+
// **render** is the core function that your view should override, in order
|
1263
|
+
// to populate its element (`this.el`), with the appropriate HTML. The
|
1264
|
+
// convention is for **render** to always return `this`.
|
1265
|
+
render: function() {
|
1266
|
+
return this;
|
1267
|
+
},
|
1268
|
+
|
1269
|
+
// Remove this view by taking the element out of the DOM, and removing any
|
1270
|
+
// applicable Backbone.Events listeners.
|
1271
|
+
remove: function() {
|
1272
|
+
this.$el.remove();
|
1273
|
+
this.stopListening();
|
1274
|
+
return this;
|
1275
|
+
},
|
1276
|
+
|
1277
|
+
// Change the view's element (`this.el` property), including event
|
1278
|
+
// re-delegation.
|
1279
|
+
setElement: function(element, delegate) {
|
1280
|
+
if (this.$el) this.undelegateEvents();
|
1281
|
+
this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
|
1282
|
+
this.el = this.$el[0];
|
1283
|
+
if (delegate !== false) this.delegateEvents();
|
1284
|
+
return this;
|
1285
|
+
},
|
1286
|
+
|
1287
|
+
// Set callbacks, where `this.events` is a hash of
|
1288
|
+
//
|
1289
|
+
// *{"event selector": "callback"}*
|
1290
|
+
//
|
1291
|
+
// {
|
1292
|
+
// 'mousedown .title': 'edit',
|
1293
|
+
// 'click .button': 'save'
|
1294
|
+
// 'click .open': function(e) { ... }
|
1295
|
+
// }
|
1296
|
+
//
|
1297
|
+
// pairs. Callbacks will be bound to the view, with `this` set properly.
|
1298
|
+
// Uses event delegation for efficiency.
|
1299
|
+
// Omitting the selector binds the event to `this.el`.
|
1300
|
+
// This only works for delegate-able events: not `focus`, `blur`, and
|
1301
|
+
// not `change`, `submit`, and `reset` in Internet Explorer.
|
1302
|
+
delegateEvents: function(events) {
|
1303
|
+
if (!(events || (events = _.result(this, 'events')))) return;
|
1304
|
+
this.undelegateEvents();
|
1305
|
+
for (var key in events) {
|
1306
|
+
var method = events[key];
|
1307
|
+
if (!_.isFunction(method)) method = this[events[key]];
|
1308
|
+
if (!method) throw new Error('Method "' + events[key] + '" does not exist');
|
1309
|
+
var match = key.match(delegateEventSplitter);
|
1310
|
+
var eventName = match[1], selector = match[2];
|
1311
|
+
method = _.bind(method, this);
|
1312
|
+
eventName += '.delegateEvents' + this.cid;
|
1313
|
+
if (selector === '') {
|
1314
|
+
this.$el.on(eventName, method);
|
1315
|
+
} else {
|
1316
|
+
this.$el.on(eventName, selector, method);
|
1317
|
+
}
|
1318
|
+
}
|
1319
|
+
},
|
1320
|
+
|
1321
|
+
// Clears all callbacks previously bound to the view with `delegateEvents`.
|
1322
|
+
// You usually don't need to use this, but may wish to if you have multiple
|
1323
|
+
// Backbone views attached to the same DOM element.
|
1324
|
+
undelegateEvents: function() {
|
1325
|
+
this.$el.off('.delegateEvents' + this.cid);
|
1326
|
+
},
|
1327
|
+
|
1328
|
+
// Performs the initial configuration of a View with a set of options.
|
1329
|
+
// Keys with special meaning *(model, collection, id, className)*, are
|
1330
|
+
// attached directly to the view.
|
1331
|
+
_configure: function(options) {
|
1332
|
+
if (this.options) options = _.extend({}, _.result(this, 'options'), options);
|
1333
|
+
_.extend(this, _.pick(options, viewOptions));
|
1334
|
+
this.options = options;
|
1335
|
+
},
|
1336
|
+
|
1337
|
+
// Ensure that the View has a DOM element to render into.
|
1338
|
+
// If `this.el` is a string, pass it through `$()`, take the first
|
1339
|
+
// matching element, and re-assign it to `el`. Otherwise, create
|
1340
|
+
// an element from the `id`, `className` and `tagName` properties.
|
1341
|
+
_ensureElement: function() {
|
1342
|
+
if (!this.el) {
|
1343
|
+
var attrs = _.extend({}, _.result(this, 'attributes'));
|
1344
|
+
if (this.id) attrs.id = _.result(this, 'id');
|
1345
|
+
if (this.className) attrs['class'] = _.result(this, 'className');
|
1346
|
+
var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs);
|
1347
|
+
this.setElement($el, false);
|
1348
|
+
} else {
|
1349
|
+
this.setElement(_.result(this, 'el'), false);
|
1350
|
+
}
|
1351
|
+
}
|
1352
|
+
|
1353
|
+
});
|
1354
|
+
|
1355
|
+
// Backbone.sync
|
1356
|
+
// -------------
|
1357
|
+
|
1358
|
+
// Map from CRUD to HTTP for our default `Backbone.sync` implementation.
|
1359
|
+
var methodMap = {
|
1360
|
+
'create': 'POST',
|
1361
|
+
'update': 'PUT',
|
1362
|
+
'patch': 'PATCH',
|
1363
|
+
'delete': 'DELETE',
|
1364
|
+
'read': 'GET'
|
1365
|
+
};
|
1366
|
+
|
1367
|
+
// Override this function to change the manner in which Backbone persists
|
1368
|
+
// models to the server. You will be passed the type of request, and the
|
1369
|
+
// model in question. By default, makes a RESTful Ajax request
|
1370
|
+
// to the model's `url()`. Some possible customizations could be:
|
1371
|
+
//
|
1372
|
+
// * Use `setTimeout` to batch rapid-fire updates into a single request.
|
1373
|
+
// * Send up the models as XML instead of JSON.
|
1374
|
+
// * Persist models via WebSockets instead of Ajax.
|
1375
|
+
//
|
1376
|
+
// Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
|
1377
|
+
// as `POST`, with a `_method` parameter containing the true HTTP method,
|
1378
|
+
// as well as all requests with the body as `application/x-www-form-urlencoded`
|
1379
|
+
// instead of `application/json` with the model in a param named `model`.
|
1380
|
+
// Useful when interfacing with server-side languages like **PHP** that make
|
1381
|
+
// it difficult to read the body of `PUT` requests.
|
1382
|
+
Backbone.sync = function(method, model, options) {
|
1383
|
+
var type = methodMap[method];
|
1384
|
+
|
1385
|
+
// Default options, unless specified.
|
1386
|
+
_.defaults(options || (options = {}), {
|
1387
|
+
emulateHTTP: Backbone.emulateHTTP,
|
1388
|
+
emulateJSON: Backbone.emulateJSON
|
1389
|
+
});
|
1390
|
+
|
1391
|
+
// Default JSON-request options.
|
1392
|
+
var params = {type: type, dataType: 'json'};
|
1393
|
+
|
1394
|
+
// Ensure that we have a URL.
|
1395
|
+
if (!options.url) {
|
1396
|
+
params.url = _.result(model, 'url') || urlError();
|
1397
|
+
}
|
1398
|
+
|
1399
|
+
// Ensure that we have the appropriate request data.
|
1400
|
+
if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
|
1401
|
+
params.contentType = 'application/json';
|
1402
|
+
params.data = JSON.stringify(options.attrs || model.toJSON(options));
|
1403
|
+
}
|
1404
|
+
|
1405
|
+
// For older servers, emulate JSON by encoding the request into an HTML-form.
|
1406
|
+
if (options.emulateJSON) {
|
1407
|
+
params.contentType = 'application/x-www-form-urlencoded';
|
1408
|
+
params.data = params.data ? {model: params.data} : {};
|
1409
|
+
}
|
1410
|
+
|
1411
|
+
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
|
1412
|
+
// And an `X-HTTP-Method-Override` header.
|
1413
|
+
if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
|
1414
|
+
params.type = 'POST';
|
1415
|
+
if (options.emulateJSON) params.data._method = type;
|
1416
|
+
var beforeSend = options.beforeSend;
|
1417
|
+
options.beforeSend = function(xhr) {
|
1418
|
+
xhr.setRequestHeader('X-HTTP-Method-Override', type);
|
1419
|
+
if (beforeSend) return beforeSend.apply(this, arguments);
|
1420
|
+
};
|
1421
|
+
}
|
1422
|
+
|
1423
|
+
// Don't process data on a non-GET request.
|
1424
|
+
if (params.type !== 'GET' && !options.emulateJSON) {
|
1425
|
+
params.processData = false;
|
1426
|
+
}
|
1427
|
+
|
1428
|
+
var success = options.success;
|
1429
|
+
options.success = function(resp) {
|
1430
|
+
if (success) success(model, resp, options);
|
1431
|
+
model.trigger('sync', model, resp, options);
|
1432
|
+
};
|
1433
|
+
|
1434
|
+
var error = options.error;
|
1435
|
+
options.error = function(xhr) {
|
1436
|
+
if (error) error(model, xhr, options);
|
1437
|
+
model.trigger('error', model, xhr, options);
|
1438
|
+
};
|
1439
|
+
|
1440
|
+
// Make the request, allowing the user to override any Ajax options.
|
1441
|
+
var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
|
1442
|
+
model.trigger('request', model, xhr, options);
|
1443
|
+
return xhr;
|
1444
|
+
};
|
1445
|
+
|
1446
|
+
// Set the default implementation of `Backbone.ajax` to proxy through to `$`.
|
1447
|
+
Backbone.ajax = function() {
|
1448
|
+
return Backbone.$.ajax.apply(Backbone.$, arguments);
|
1449
|
+
};
|
1450
|
+
|
1451
|
+
// Helpers
|
1452
|
+
// -------
|
1453
|
+
|
1454
|
+
// Helper function to correctly set up the prototype chain, for subclasses.
|
1455
|
+
// Similar to `goog.inherits`, but uses a hash of prototype properties and
|
1456
|
+
// class properties to be extended.
|
1457
|
+
var extend = function(protoProps, staticProps) {
|
1458
|
+
var parent = this;
|
1459
|
+
var child;
|
1460
|
+
|
1461
|
+
// The constructor function for the new subclass is either defined by you
|
1462
|
+
// (the "constructor" property in your `extend` definition), or defaulted
|
1463
|
+
// by us to simply call the parent's constructor.
|
1464
|
+
if (protoProps && _.has(protoProps, 'constructor')) {
|
1465
|
+
child = protoProps.constructor;
|
1466
|
+
} else {
|
1467
|
+
child = function(){ return parent.apply(this, arguments); };
|
1468
|
+
}
|
1469
|
+
|
1470
|
+
// Add static properties to the constructor function, if supplied.
|
1471
|
+
_.extend(child, parent, staticProps);
|
1472
|
+
|
1473
|
+
// Set the prototype chain to inherit from `parent`, without calling
|
1474
|
+
// `parent`'s constructor function.
|
1475
|
+
var Surrogate = function(){ this.constructor = child; };
|
1476
|
+
Surrogate.prototype = parent.prototype;
|
1477
|
+
child.prototype = new Surrogate;
|
1478
|
+
|
1479
|
+
// Add prototype properties (instance properties) to the subclass,
|
1480
|
+
// if supplied.
|
1481
|
+
if (protoProps) _.extend(child.prototype, protoProps);
|
1482
|
+
|
1483
|
+
// Set a convenience property in case the parent's prototype is needed
|
1484
|
+
// later.
|
1485
|
+
child.__super__ = parent.prototype;
|
1486
|
+
|
1487
|
+
return child;
|
1488
|
+
};
|
1489
|
+
|
1490
|
+
// Set up inheritance for the model, collection, router, view and history.
|
1491
|
+
Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;
|
1492
|
+
|
1493
|
+
// Throw an error when a URL is needed, and none is supplied.
|
1494
|
+
var urlError = function() {
|
1495
|
+
throw new Error('A "url" property or function must be specified');
|
1496
|
+
};
|
1497
|
+
|
1498
|
+
}).call(this);
|