Skip to content

Commit 24a506a

Browse files
committed
Re-wrote ajax to request to be modular
1 parent 23e8142 commit 24a506a

File tree

1 file changed

+57
-17
lines changed

1 file changed

+57
-17
lines changed

application/views/rest_server.php

Lines changed: 57 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -118,31 +118,71 @@
118118
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
119119

120120
<script>
121-
$(function() {
121+
// Create an 'App' namespace
122+
var App = App || {};
122123

123-
$('#ajax').on('click', function (event) {
124+
// Basic rest module using an IIFE as a way of enclosing private variables
125+
App.rest = (function ($, window) {
126+
// Fields
124127

125-
event.preventDefault();
128+
// Cache the jQuery selector
129+
var $_ajax = null;
126130

127-
$.ajax({
128-
129-
// URL from the link that was clicked on.
130-
url: $(this).attr('href')
131-
132-
}).done(function (data) {
133-
134-
// The 'data' parameter is an array of objects that can be looped over.
131+
// Methods (private)
135132

136-
alert(JSON.stringify(data));
133+
// Called on Ajax done
134+
function ajaxDone(data) {
135+
// The 'data' parameter is an array of objects that can be iterated over
136+
window.alert(JSON.stringify(data, null, 2));
137+
}
137138

138-
}).fail(function () {
139-
140-
alert('Oh no! A problem with the Ajax request!');
139+
// Called on Ajax fail
140+
function ajaxFail() {
141+
window.alert('Oh no! A problem with the Ajax request!');
142+
}
141143

144+
// On Ajax request
145+
function ajaxEvent($this) {
146+
$.ajax({
147+
// URL from the link that was 'clicked' on
148+
url: $this.attr('href')
149+
})
150+
.done(ajaxDone)
151+
.fail(ajaxFail);
152+
}
153+
154+
// Bind event(s)
155+
function bind() {
156+
// Namespace the 'click' event
157+
$_ajax.on('click.app.rest.module', function (event) {
158+
event.preventDefault();
159+
160+
// Pass this to the Ajax event function
161+
ajaxEvent($(this));
142162
});
143-
});
144-
163+
}
164+
165+
// Cache the DOM node(s)
166+
function cacheDom() {
167+
$_ajax = $('#ajax');
168+
}
169+
170+
// Public API
171+
return {
172+
init: function () {
173+
// Cache the DOM and bind event(s)
174+
cacheDom();
175+
bind();
176+
}
177+
};
178+
})(jQuery, window);
179+
180+
// DOM ready event
181+
$(function () {
182+
// Initialise the App module
183+
App.rest.init();
145184
});
185+
146186
</script>
147187

148188
</body>

0 commit comments

Comments
 (0)