· 9 years ago · Dec 01, 2016, 05:32 PM
1function startApp() {
2
3 let self = this;
4 let appKey = 'kid_rkax2fPfe';
5 let secretKey = 'b2c7b757fbd14ade9193ed9439c7121c';
6
7 $(document).on({
8 ajaxStart : () => { $('#loadingBox').show(); },
9 ajaxStop : () => { $('#loadingBox').hide(); }
10 });
11
12 /*
13 * Links
14 */
15 let nonLoggedUserLinks = [
16 '#linkHome',
17 '#linkLogin',
18 '#linkRegister',
19 '#viewHome'
20 ];
21
22 let loggedUserLinks = [
23 '#linkHome',
24 '#linkHome',
25 '#linkListAds',
26 '#linkCreateAd',
27 '#linkLogout',
28 '#loggedInUser',
29 ];
30
31 //
32 // Bind buttons
33 //
34
35 $('#formLogin').submit(login);
36 $('#formRegister').submit(register);
37 $('#formCreateAd').submit(create);
38 $('#formEditAd').submit(editAdvert)
39
40 // The Routes
41 let routes = {
42 'linkHome' : '#viewHome',
43 'linkLogin' : '#viewLogin',
44 'linkRegister' : '#viewRegister',
45 'linkListAds' : '#viewAds',
46 'linkCreateAd' : '#viewCreateAd',
47 'linkLogout' : '#viewHome'
48 };
49
50 function loadView () {
51
52 // Click Menu Item
53 $('#menu').find('a').on('click', function(e) {
54 e.preventDefault();
55
56 let id = $(this).attr('id');
57
58 $('main section').hide();
59 $(routes[id]).show();
60
61 if( $('#viewAds').css("display") == 'block' )
62 list();
63
64 if( id == 'linkLogout' )
65 logout();
66 });
67 }
68
69 function renderLinks() {
70
71 $('header a, header #loggedInUser').hide();
72 let user = JSON.parse(localStorage.getItem('user'));
73
74 if(user == null)
75 {
76 nonLoggedUserLinks.map( (x) => { $(x).show(); });
77 }
78 else {
79
80 loggedUserLinks.map( (x) => { $(x).show(); });
81 $('#loggedInUser').show().text( user.username );
82 }
83 }
84
85 // Window onload
86 // edited
87 $(window).on('load', (x) => {
88 renderLinks();
89 loadView();
90 $('main section').hide();
91 $('main #viewHome').show();
92 });
93
94 //
95 // Views
96 //
97
98 function viewEditAdvert(advert) {
99 $('main section').hide();
100 $('#viewEditAd').find('input[name="id"]').val(advert._id);
101 $('#viewEditAd').find('input[name="title"]').val(advert.title);
102 $('#viewEditAd').find('input[name="publisher"]').val(advert.publisher);
103 $('#viewEditAd').find('input[name="datePublished"]').val(advert.datePublished);
104 $('#viewEditAd').find('input[name="price"]').val(Number(advert.price));
105 $('#viewEditAd').find('textarea[name="description"]').val(advert.description);
106 $('#viewEditAd').show();
107 };
108
109 //
110 // Adverts CRUD
111 //
112
113 // Create - C
114 // edited
115 function create(event) {
116 // HERE:
117 event.preventDefault();
118 let form = $('#formCreateAd');
119 let user = JSON.parse( localStorage.getItem('user') );
120
121 let advert = {
122 'title' : form.find('input[name="title"]').val(),
123 'description' : form.find('textarea[name="description"]').val(),
124 'datePublished' : form.find('input[name="datePublished"]').val(),
125 'price' : form.find('input[name="price"]').val(),
126 'publisher' : user.username
127 };
128 // HERE:
129 // now you do not need this kind of verification
130 // since we are now using the submit of the form
131 // and the required fields are working properly
132 $.ajax({
133 type: 'POST',
134 url : 'https://baas.kinvey.com/appdata/'+ appKey +'/books',
135 headers : {
136 'Authorization' : 'Kinvey' + ' ' + user.authtoken
137 },
138 data : advert,
139 success: function (res) {
140
141 Promise.all([list()])
142 .then(() => {
143 $('main section').hide(),
144 $('main #viewAds').show()
145 $('#infoBox').show()
146 .html(`<strong>${res.title}</strong> was added successfully!`)
147 .fadeOut(3000);
148 })
149 .catch(error => console.log(error));
150
151
152
153 },
154 error: function(error) {
155 console.log(error);
156 }
157 });
158 // HERE:
159 $(event.target).trigger('reset');
160 }
161
162 // Read - R
163 // edited
164 function list() {
165 let table = $('#viewAds').find('table tbody');
166 let user = JSON.parse( localStorage.getItem('user') );
167
168 $.ajax({
169 type: 'GET',
170 url : 'https://baas.kinvey.com/appdata/'+ appKey +'/books',
171 headers : {
172 'Authorization' : 'Kinvey' + ' ' + user.authtoken
173 },
174 success: function (ads) {
175 // HERE:
176 // using the if like this we avoid lots of indenting
177 // which keeps the code nice and clean, easy to read
178 if (ads.length == 0) {
179 table.append(`<tr><td colspan="5">No data to display.</td></tr>`);
180 return;
181 }
182 let tH = table.find('tr:first-child');
183 table.empty();
184 table.append(tH);
185 // HERE:
186 // the convention of javascript block brackets is as follows
187 // operation() {
188 // (code)
189 // }
190 for(let i in ads) {
191 let tr = $('<tr>')
192 .append( $('<input type="hidden" name="_id" />').val(ads[i]._id) )
193 .append( $('<td>').text(ads[i].title) )
194 .append( $('<td>').text(ads[i].publisher) )
195 .append( $('<td>').text(ads[i].description) )
196 .append( $('<td>').text(ads[i].price) )
197 .append( $('<td>').text(ads[i].datePublished) )
198 .append( $('<td>')
199 .append($('<a href="#">[Delete]</a>')
200 .on('click', function(event) {
201 let thisTr = $(this).closest('tr');
202 deleteAdvert( thisTr.find('input[name="_id"]').val(), function() {
203 $('#infoBox').fadeOut(3000, function () {
204 $(this).hide();
205 });
206 thisTr.remove();
207
208 if( $('#viewAds table').find('tr').length == 1 )
209 $('#viewAds table').append(`<tr><td colspan="5">No data to display.</td></tr>`);
210 });
211 })
212 )
213 // HERE:
214 .append( $('<a href="#">[Edit]</a>').on('click', function(event) {
215 viewEditAdvert(ads[i])
216 }))
217 );
218 table.append(tr);
219 }
220
221 },
222 error: function(error) {
223 console.log(error);
224 }
225 });
226
227 }
228
229 // Update - U
230 // edited
231 function editAdvert(event) {
232 // HERE:
233 event.preventDefault();
234 let form = $('#formEditAd');
235 let user = JSON.parse( localStorage.getItem('user') );
236 // HERE:
237 let id = $('#viewEditAd').find('input[name="id"]').val();
238
239 let data = {
240 'title' : form.find('input[name="title"]').val(),
241 'description' : form.find('textarea[name="description"]').val(),
242 'datePublished' : form.find('input[name="datePublished"]').val(),
243 'price' : form.find('input[name="price"]').val(),
244 'publisher' : user.username
245 };
246
247 $.ajax({
248 type: 'PUT',
249 url : 'https://baas.kinvey.com/appdata/'+ appKey +'/books/' + id,
250 headers : {
251 'Authorization' : 'Kinvey' + ' ' + user.authtoken,
252 },
253 data : data,
254 success: function (res) {
255 // HERE:
256 $('main section').hide()
257 Promise.all([list()])
258 .then(() => {
259 $('main #viewAds').show()
260 $('#infoBox').show()
261 .html(`<strong>${res.title}</strong> was successfully edited!`)
262 .fadeOut(3000, function() {
263 $(this).hide();
264 });
265 });
266
267 },
268 error: function(error) {
269 console.log(error);
270 }
271 });
272 // HERE:
273 $(event.target).trigger('reset');
274 }
275
276 // Delete - D
277 function deleteAdvert(_id, FUNC) {
278
279 let user = JSON.parse( localStorage.getItem('user') );
280 $.ajax({
281 url: 'https://baas.kinvey.com/appdata/' + appKey + '/books/' + _id,
282 type: 'DELETE',
283 headers : {
284 'Authorization' : 'Kinvey ' + user.authtoken
285 },
286 success: function (edited) {
287
288 console.log( edited );
289 $('#infoBox').text('Item successfully deleted!').show();
290 FUNC();
291 },
292 error: function (error) {
293
294 console.log( error );
295 }
296 });
297
298 }
299
300 //
301 // User
302 //
303
304 // edited
305 function saveUser(user) {
306 let temp = {
307 'authtoken' : user._kmd.authtoken,
308 'username' : user.username
309 }
310 localStorage.setItem('user', JSON.stringify(temp));
311 }
312
313 function authUser() {
314
315 return JSON.parse( localStorage.getItem('user') );
316 }
317
318 // edited
319 function login(event) {
320 // HERE:
321 // prevents reloading of the current page
322 // when submit is invoked
323 event.preventDefault();
324
325 let inputs = {
326 'username' : $('#formLogin').find('input[name="username"]').val(),
327 'password' : $('#formLogin').find('input[name="passwd"]').val(),
328 };
329
330 $.ajax({
331 url: 'https://baas.kinvey.com/user/' + appKey + '/login',
332 type: 'POST',
333 headers : {
334 'Authorization' : 'Basic ' + btoa(appKey + ':' + secretKey)
335 },
336 data: inputs,
337
338 success: function (user) { // changed User to user due to convention
339 // removed user declaration and moved logic to saveUser function
340 saveUser(user);
341
342 renderLinks();
343 $('main section').hide();
344 $('main #viewHome').show();
345
346 },
347 error: function (error) {
348 console.log( error );
349 }
350 });
351 // HERE:
352 // cleares the login form fields
353 // because we are using a single-page app
354 // and if we didn't clear it the app will be
355 // full of all sorts of outdated data lying around
356 // event.target is the form itself as in <form id="formLogin">(...)</form>
357 $(event.target).trigger('reset');
358 console.log(inputs);
359 }
360
361 // edited
362 function register(event) {
363 // HERE:
364 // prevents reloading of the current page
365 // when submit is invoked
366 event.preventDefault();
367
368 let inputs = {
369 'username' : $('#formRegister').find('input[name="username"]').val(),
370 'password' : $('#formRegister').find('input[name="passwd"]').val(),
371 };
372
373 $.ajax({
374 url: 'https://baas.kinvey.com/user/' + appKey,
375 type: 'POST',
376 headers : {
377 'Authorization' : 'Basic ' + btoa(appKey + ':' + secretKey)
378 },
379 data: inputs,
380 // HERE:
381 success: function (user) { // changed User to user due to convention
382 // removed user declaration and moved logic to saveUser function
383 saveUser(user);
384 $('main section').hide();
385 $('main #viewLogin').show();
386 },
387 error: function (error) {
388 console.log( error );
389 }
390 });
391 // HERE:
392 // cleares the register form fields
393 // because we are using a single-page app
394 // and if we didn't clear it the app will be
395 // full of all sorts of outdated data lying around
396 // event.target is the form itself as in <form id="formRegister">(...)</form>
397 $(event.target).trigger('reset');
398 console.log(inputs);
399 }
400
401 // edited
402 function logout() {
403 var user = JSON.parse( localStorage.getItem('user') );
404
405 $.ajax({
406 type: 'POST',
407 url : 'https://baas.kinvey.com/user/'+ appKey +'/_logout',
408 headers : {
409 'Authorization' : 'Kinvey' + ' ' + user.authtoken
410 },
411 success: function (res) {
412 console.log(res);
413 localStorage.removeItem('user');
414 renderLinks();
415 }
416 });
417 }
418}