-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplication.js
More file actions
82 lines (69 loc) · 2.18 KB
/
application.js
File metadata and controls
82 lines (69 loc) · 2.18 KB
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
// Code based on http://addyosmani.com/largescalejavascript/ And the design
// patterns book
// http://addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatternsjavascript
var mediator = (function() {
var subscribe = function(channel, fn){
if (!mediator.channels[channel]) {
mediator.channels[channel] = [];
}
mediator.channels[channel].push({ context: this, callback: fn });
return this;
};
var publish = function(channel){
if (!mediator.channels[channel]) return false;
var args = Array.prototype.slice.call(arguments, 1);
for (var i = 0, l = mediator.channels[channel].length; i < l; i++) {
var subscription = mediator.channels[channel][i];
subscription.callback.apply(subscription.context, args);
}
return this;
};
return {
channels: {},
publish: publish,
subscribe: subscribe,
installTo: function(obj) {
obj.subscribe = subscribe;
obj.publish = publish;
}
};
}());
var github = (function() {
var httpRequest = new XMLHttpRequest();
var publishAjaxCompleted = function() {
if (httpRequest.readyState === 4 && httpRequest.status === 200) {
mediator.publish('refreshUser', JSON.parse(httpRequest.responseText));
}
};
var getUser = function (user) {
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = publishAjaxCompleted;
httpRequest.open('GET', 'https://api.github.com/users/' + user);
httpRequest.send();
};
return {
getUser: getUser
};
}());
var ui = (function() {
var refresh = function(data) {
updatableArea = document.querySelector('#updatableArea');
updatableArea.innerHTML = data.login;
updatableArea.innerHTML += "<img src='"+data.avatar_url+"'>";
};
return {
user: {
refresh: refresh
}
}
}());
window.onload = function() {
//Pub/sub on a centralized mediator
mediator.subscribe('refreshUser', ui.user.refresh);
mediator.subscribe('updateClick', github.getUser);
updateButton = document.querySelector('#updateButton');
updateButton.addEventListener('click', function() {
userName = document.querySelector('#githubUser').value;
mediator.publish('updateClick', userName);
});
};