-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.django.js
376 lines (347 loc) · 14.8 KB
/
jquery.django.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
(function($) {
$.django = function(method){
var methods = {
init : function(options) {
var popped, initialUrl; // for popstate event listener
var settings = $.extend({
'urls' : [],
'no_match' : function(url){
window.location = url;
},
'active': []
}, options);
$(window).data('django', settings);
// need to handle the incorrect event fired by some browsers:
popped = ('state' in window.history);
initialURL = location.href
$(window).bind('popstate', function(){
var initialPop = (popped && location.href === initialURL);
popped = false;
if ( initialPop ) {
return;
}
$.django('statechange')
});
$.django('anchors');
/* TODO -- some browsers fire the popstate event immediately upon page load,
meaning that inital view will be loaded twice since there are 2 calls to
$.django('statechange')
*/
$(window).data('django').was_popped = ('state' in window.history);
$(window).data('django').initial = location.href;
$.django('statechange', false);
return this;
},
pushstate : function(obj, title, url){
/*
TODO -- determine workaround for browser compatibility if the browser doesn't support
pushState yet
*/
window.history.pushState(obj, title, url);
$.django('statechange', obj);
return this;
},
statechange : function(obj){
/*
Called when the url is changed and a new view should be called
*/
//var initialPop = !$(window).data('django').popped && location.href == $(window).data('django').initial;
//$(window).data('django').popped = true;
//if (initialPop) return false;
if (!$(window).data('django').urls) return $.error('No URLS defined!');
var url = $.django('url');
for (var i in $(window).data('django').urls){
var match = url.match($(window).data('django').urls[i].url);
if (match) {
if ($(window).data('django').urls[i].redirect){
return $.django('pushstate', {}, '',
$.django('url', $(window).data('django').urls[i].redirect));
}
else{
var view = $(window).data('django').urls[i].view;
var requirements = $.django('requirements', view);
var active = $.extend(true, [], $(window).data('django').active);
// unload neccesary instances
for (var i=0; i<active.length; i++){
var remove = true;
for (var ii=0; ii<requirements.length; ii++){
if (active[i] instanceof requirements[ii]){
remove = false;
}
}
if (remove) $.django('unload', active[i]);
}
// load neccesary views
return $.django('load', view, match);
}
}
}
return $(window).data('django').no_match.call(obj, url);
},
anchors : function() {
/*
Hijack all the the pages anchors and attach a event handler
that updates the page's location via a pushState change instead of
actually reloading the page
This is run after each view is loaded, and must also be run anytime that new
HTML (with new anchor tags) is inserted into the page (be it via ajax, etc)
*/
$('a').off('click.django');
$('a').on('click.django', function(){
var bad_prefixes = ['#', 'javascript:'];
var hijack = false;
if ($(this).attr('TARGET')) return true;
if ($(this).attr('href')){
for (var i=0;i<bad_prefixes.length;i++){
if ($(this).attr('href').indexOf(bad_prefixes[i]) == 0) return true;
}
hijack = true;
try{
$.django('pushstate', {}, '', $(this).attr('href'));
}
catch (e) {
$.error(e) ;
}
}
return (!hijack);
});
if ($(window).data('django').anchor_callback) {
$(window).data('django').anchor_callback.call();
}
},
load : function(view, match) {
/*
Does the work for loading a new view
For each view, it is the author of a view's responsibility to impliment
a method called 'load'. Into the load method are passed the
parameters that came from the regular expression match
of the page's URL.
e.g. Let's say that your URL pattern has the
form /article/50/ where "50" in this case represents an variable ID
that your view would require.
The regex for this url may look like:
/\/article\/(.[^\/]*)\/?/
And the view would look like:
function myView(){
this.render = function(url, article_id){
// do something
}
}
If a view is a "subview", and thus requires that another view be loaded
before it is called, simply set the 'requires' attribute of the object to
the view that needs to be loaded first. Note, this will render the required
view first, and in a synchronous manner, before loading the current view. In order
to accomplish this (and if synchronicity is important to you), ensure that
the return from the load method returns a deferred (new in jquery 1.5) that will
resolve when the next view is ready to be loaded.
Good article on deferreds: http://www.erichynds.com/jquery/using-deferreds-in-jquery/
e.g.
var mySubView = function(){
this.requires = myBaseView
this.load = function(){
var deferred = $.Deferred();
$.when($.ajax('/api')).done(function(){
// do something...
deferred.resolve();
})
return deferred;
}
}
Also, by setting the 'title' attribute of a view object, the window's title will be updated
upon rendering
*/
if (!view) return true;
if ($.django('isloaded', view)){
$.django('reload', view, match);
return true;
}
var instance = new view();
return function(defer){
$.when($.django('load', instance.requires, match)).done(
function(view, match){
return function(){
var d = view.load.apply(view, match);
$(window).data('django').active.push(view);
$.when(d).done(function(){
defer.resolve();
if (view.title) document.title = view.title;
return $.django('anchors');
});
}
}(instance, match));
return defer;
}($.Deferred());
},
unload: function(instance){
/*
(Optional) Called when a view is destroyed.
*/
var active = $.extend(true, [], $(window).data('django').active);
for (var i in active){
if (active[i] == instance){
$(window).data('django').active.splice(i, 1);
}
}
if (instance.unload) instance.unload.call(instance);
},
reload: function(view, match){
/*
(Optional) Called when a loaded again
*/
var active = $.extend(true, [], $(window).data('django').active);
for (var i=0; i<active.length; i++){
if (active[i] instanceof view){
if (active[i].reload) active[i].reload.apply(active[i], match);
}
}
},
isloaded: function(view){
var active = $.extend(true, [], $(window).data('django').active);
for (var i=0; i<active.length; i++){
if (active[i] instanceof view) return true;
}
return false;
},
requirements: function(view){
/*
Recusively iterates thru a view's list of required subviews and returns
a list of each required view (plus itself).
This is used for determining what views to unload upon a new statechange -- you
probably won't ever need to call this method externally
*/
var i = new view();
if (!i.requires) return [view]
else return [view].concat($.django('requirements', i.requires));
},
url : function(name, params){
/*
Return the url, as a string, for a view given the view's 'name' attribute.
*/
if (!name) return window.location.pathname;
for (var i in $(window).data('django').urls){
if ($(window).data('django').urls[i].name == name){
return $.django('reverse', $(window).data('django').urls[i].url, params);
}
}
},
reverse : function(regex, params) {
/*
Super bootleg -- I can't find another better method though. Please help.
*/
params = params || [];
var s = String(regex);
s = s.substr(1, s.length - 2);
s = s.replace(/\\/g, '');
s = s.replace(/\?/g, '');
s = s.replace(/\$/g, '');
var matches = s.match(/\(.*\)\??/) || [];
for (var i=0; i<matches.length; i++){
var param = '';
if (params[i] !== null) param = String(params[i]);
s = s.replace(matches[i], param);
}
return s;
},
toggle : function(x) {
/*
Useful function for toggling state between a group of HTML elements
Common example is changing the class of a link when it is "active"
@input
x.group -- jquery selection of elements e.g. $('#nav li')
x.select -- function called on each element from x.group and returns
true/false to signify whether or not the element is "active"
e.g. function(){ return this.html() == 'Home' }
x.active -- function called on each element that is considered "active"
e.g. function(){ this.addClass('active') }
x.inactive -- function called on each element that is considered "inactive"
e.g. function(){ this.removeClass('active') }
*/
$(x.group).each(function(index, element){
if (x.select.call($(element))) x.active.call($(element));
else x.inactive.call($(element));
})
},
model : function(options){
this.attr = function(name){
var f = function(obj, attr){
this.save = function(){
obj.attrs[attr].old = obj.attrs[attr].val;
}
this.revert = function(){
obj.attrs[attr].val = obj.attrs[attr].old;
this.update();
}
this.val = function(value){
if (value === undefined) return obj.attrs[attr].val;
if (!obj.attrs[attr].val){
obj.attrs[attr].val = value;
obj.attrs[attr].old = value;
}
else{
obj.attrs[attr].val = value;
}
this.update();
}
this.html = function(){
return '<span class="'+this.class()+'">'+this.val()+'</span>';
}
this.update = function(){
$('.'+this.class()).html(this.val());
}
this.class = function(){
return 'model_' + obj.uid + '_' + name;
}
this.follow = function(input){
input.on('keyup', function(e){
if (e.keyCode == 27) return;
obj.attr(attr).val($(e.srcElement).val());
});
}
if (!obj.attrs) obj.attrs = {};
if (!obj.attrs[name]){
obj.attrs[name] = {
val: null,
old: null
}
}
return this;
}
f.prototype.toString = function(){
return this.val();
}
return new f(this, name);
},
this.revert = function(){
for (var name in this.attrs){
this.attr(name).revert();
}
},
this.save = function(data){
if (data){
for (var key in data){
this.attr(key).val(data[key]);
}
}
for (var name in this.attrs){
this.attr(name).save();
}
},
this.update = function(){
for (var name in this.attrs){
this.attr(name).update();
}
}
}
};
// Method calling logic
if (methods[method]){
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
}
else if (typeof method === 'object' || ! method){
return methods.init.apply( this, arguments );
}
else {
$.error( 'Method ' + method + ' does not exist on jQuery.django' );
}
}
})(jQuery);