-
Notifications
You must be signed in to change notification settings - Fork 3
/
Location.coffee
98 lines (67 loc) · 2.14 KB
/
Location.coffee
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
package "cafe"
Location: class Location
location: null
href : null
host : null
path : null
protocol: null
search : null
port : null
hash : null
changeHashListeners: null
constructor: (@location=document.location) ->
{location} = @
@changeHashListeners = []
@href = location.href
@host = location.hostname
@path = location.pathname
@protocol = location.protocol.replace(/:$/, "")
@search = {}
for pare in location.search.replace(/^\?/, "").split("&")
[key, value] = pare.split("=")
# todo: дописать расширение на вложенный массив
value = null if typeof value is "undefined"
@search[key] = value
@port = location.port | 0 or 80
@hash = location.hash
@hashDiffTimeout()
hashDiffTimeout: () ->
hash = document.location.hash
@processNewHash(hash) unless @hash is hash
setTimeout(
=>
@hashDiffTimeout()
10
)
processNewHash: (hash) ->
@hash = hash
for listener in @changeHashListeners
listener() if typeof listener is "function"
@instance: null
@getInstance: () ->
return @instance or @instance = new Location()
@getHref: () ->
return @getInstance().href
@getHost: () ->
return @getInstance().host
@getSection: () ->
return @getInstance().path.split("/", 2).pop()
@getAction: () ->
return @getInstance().path.split("/")[2] or ""
@getPathParams: () ->
return @getInstance().path.split("/").slice(3)
@getProtocol: () ->
return @getInstance().protocol
@getSearch: (key) ->
search = @getInstance().search
if key
return null unless key of search and (value = search[key])
return numValue unless isNaN numValue = Number(value.replace(/\s+/g, ""))
return value
return search
@getPort: () ->
return @getInstance().port
@getHash: () ->
return @getInstance().hash
@onChangeHash: () ->
@getInstance().changeHashListeners.push(arguments...)