|
118 | 118 | <script src="https://code.jquery.com/jquery-1.11.3.js"></script> |
119 | 119 |
|
120 | 120 | <script> |
121 | | - $(function() { |
| 121 | + // Create an 'App' namespace |
| 122 | + var App = App || {}; |
122 | 123 |
|
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 |
124 | 127 |
|
125 | | - event.preventDefault(); |
| 128 | + // Cache the jQuery selector |
| 129 | + var $_ajax = null; |
126 | 130 |
|
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) |
135 | 132 |
|
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 | + } |
137 | 138 |
|
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 | + } |
141 | 143 |
|
| 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)); |
142 | 162 | }); |
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(); |
145 | 184 | }); |
| 185 | + |
146 | 186 | </script> |
147 | 187 |
|
148 | 188 | </body> |
|
0 commit comments