-
Notifications
You must be signed in to change notification settings - Fork 1
/
jquery.route32.js
105 lines (100 loc) · 3.99 KB
/
jquery.route32.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
/**
* Route32 --## Simple Anchor Location Router ##--
* executes callback on location hash change that matches declared routes.
* Intenteded to be use as a piece on JavaScript MVC Apps
*
* @author Rolando Garro <[email protected]>
* @requires jQuery
*/
//BEGIN..
//Requires jQuery
if(typeof jQuery != "undefined"){
/* begin Route32 */
function Route32(options){
//Settings
var settings = $.extend({
'automatic':true,
'selector':'.nav'
},options);
//array of hashes containing hashsregexpstr,callbackfunc pairs
var routes = [];
var activeHash = '';
//methods
var methods = {
//initial method
'init':function(){
window.onhashchange = function(evt){
activeHash = "#" + evt.newURL.split("#")[1];
//activeHash = methods.getHashValue();
};
},
//verifies is string is a valid location hash
'isValidHash':function(hashStr){
return true;
},
'isValidCallbackfunc':function(callbackfunc){
if(typeof callbackfunc == "function"){
return true;
}else{
return false;
}
},
'getHashValue':function(evt){
//return window.location.hash;
return "#" + evt.newURL.split("#")[1]
},
'executeCurrent':function(){
$.each(routes,function(index,value){
if(value.hash == activeHash){
value.callback();
}
});
}
};
//adds routes
this.add = function(hashRegexpStr,callbackfunc){
if(methods.isValidHash(hashRegexpStr) && methods.isValidCallbackfunc(callbackfunc)){
routes.push({hash:hashRegexpStr,callback:callbackfunc});
}else{
alert('route should be a valid hash string, callback function pair.');
}
};
//starts driving
this.drive = function(){
if(routes.length > 0){
if(settings.automatic){
//start listening location changes
window.onhashchange = function(evt){
activeHash = methods.getHashValue(evt);
methods.executeCurrent();
};
}else{
//listen selector click
$(settings.selector).live('click',function(){
var turn = true;
window.onhashchange = function(evt){
activeHash = methods.getHashValue(evt);
turn = false;
methods.executeCurrent();
};
if(turn){
methods.executeCurrent();
}
});
}
}else{
alert('use add method to add routes');
}
};
//executes actual route arbitrarily
this.again = function(){
methods.executeCurrent();
};
methods.init();
return this;
};
/* end Route32 */
}else{
alert("jQuery is required to ride Route32.");
}
//END..