View difference between Paste ID: BbzDdeGZ and JBcabcq7
SHOW: | | - or go back to the newest paste.
1
function startApp() {
2
    sessionStorage.clear();
3
    showHideMenuLinks();
4
    showView('viewHome');
5
6
    // Bind the navigation menu links
7
    $('#linkHome').click(showHomeView);
8
    $('#linkLogin').click(showLoginView);
9
    $('#linkRegister').click(showRegisterView);
10
    $('#linkListAds').click(showCollectionView);
11
    $('#linkCreateAd').click(showCreateView);
12
    $('#linkLogout').click(logout);
13
14
    // Bind the form submit buttons
15
    $("#formLogin").submit(login);
16
    $("#formRegister").submit(register);
17
    $("#buttonCreateAd").click(create);
18
    $("#buttonEditAd").click(edit);
19
20
    // Bind the info / error boxes: hide on click
21
    $("#infoBox, #errorBox").click(function() {
22
        $(this).fadeOut();
23
    });
24
    $(document).on({
25
        ajaxStart: function() { $("#loadingBox").show() },
26
        ajaxStop: function() { $("#loadingBox").hide() }
27
    });
28
29
    // Show or hide the links in the navigation bar
30
    function showHideMenuLinks() {
31
        $("#linkHome").show();
32
        if (sessionStorage.getItem('authToken')) {
33
            // We have logged in user
34
            $("#linkLogin").hide();
35
            $("#linkRegister").hide();
36
            $("#linkListAds").show();
37
            $("#linkCreateAd").show();
38
            $("#linkLogout").show();
39
        } else {
40
            // No logged in user
41
            $("#linkLogin").show();
42
            $("#linkRegister").show();
43
            $("#linkListAds").hide();
44
            $("#linkCreateAd").hide();
45
            $("#linkLogout").hide();
46
        }
47
    }
48
49
    // Hide all views and show the selected view only
50
    function showView(viewName) {
51
        $('main > section').hide();
52
        $('#' + viewName).show();   // viewName is the id of the given section
53
    }
54
55
    //-----Views----------------------------------------------------------------------//
56
57
    function showHomeView() {
58
        showView('viewHome');
59
    }
60
    //---------------------------
61
    function showLoginView() {
62
        showView('viewLogin');
63
        $('#formLogin').trigger('reset');
64
    }
65
    //----------------------------
66
    function showRegisterView() {
67
        showView('viewRegister');
68
        $('#formRegister').trigger('reset');
69
    }
70
    //----------------------------
71
    function showCollectionView() {
72
        $('#ads').empty();
73
        showView('viewAds');
74
        KinveyRequester.findAllEntities()
75
            .then(loadSuccess)
76
            .catch(handleAjaxError);
77
        function loadSuccess(response) {
78
            showInfo('Entities loaded.');
79
            if (response.length == 0) {
80
                $('#ads').text('The collection is empty.');
81
            }
82
            else {
83
                let table = $('<table>')
84
                    .append($('<tr>').append(
85
                        '<th>Title</th><th>Body</th><th>Author</th>,' +
86
                        '<th>Date</th><th>Actions</th>'));
87
                for (let entity of response) {
88
                    let links = [];
89
                    // action links
90
                    if (entity._acl.creator == sessionStorage['userID']) {
91
                        let deleteLink = $('<a href="#">[Delete]</a>')
92
                            .click(function () {
93
                                deleteIt(entity)
94
                            });
95
                        let editLink = $('<a href="#">[Edit]</a>')
96
                            .click(function () {
97
                                loadForEdit(entity)
98
                            });
99
                        links = [deleteLink, ' ', editLink];
100
                    }
101
102
                    table.append($('<tr>').append(
103
                        $('<td>').text(entity.title),
104
                        $('<td>').text(entity.body),
105
                        $('<td>').text(entity.author),
106
                        $('<td>').text(entity.date),
107
                        $('<td>').append(links)
108
                    ));
109
                }
110
                $('#ads').append(table);
111
            }
112
        }
113
    }
114
    //-------------------------
115
    function showCreateView() {
116
        $('#formCreateAd').trigger('reset');
117
        showView('viewCreateAd');
118
    }
119
    //--------------------------
120
    function loadForEdit(entity) {
121
        KinveyRequester.findEntityById(entity)
122
            .then(loadForEditSuccess)
123
            .catch(handleAjaxError);
124
        function loadForEditSuccess(entity) {
125
            $('#formEditAd input[name=id]').val(entity._id);
126
            $('#formEditAd input[name=title]').val(entity.title);
127
            $('#formEditAd textarea[name=description]').val(entity.body);
128
            $('#formEditAd input[name=datePublished]').val(entity.date);
129
            showView('viewEditAd');
130
        }
131
    }
132
    //-----Actions without a view------------------------------------------------------//
133
134
    function deleteIt(entity) {
135
        KinveyRequester.deleteEntity(entity)
136
            .then(deleteSuccess)
137
            .catch(handleAjaxError);
138
        function deleteSuccess() {
139
            showCollectionView();
140
            showInfo('Entity deleted.');
141
        }
142
    }
143
    //----------------------
144
    function logout() {
145
        sessionStorage.clear();
146
        $('#loggedInUser').text("");
147
        showHideMenuLinks();
148
        showView('viewHome');
149
        showInfo('Logout successful.');
150
    }
151
152
    //-----Input forms-----------------------------------------------------------------//
153
154
    function login() {
155
        event.preventDefault();
156
        let username = $('#formLogin input[name=username]').val();
157
        let password = $('#formLogin input[name=passwd]').val();
158
        KinveyRequester.loginUser(username, password)
159
            .then(loginSuccess)
160
            .catch(handleAjaxError);
161
162
        function loginSuccess(userInfo) {
163
            saveAuthInSession(userInfo);
164
            showHideMenuLinks();
165
            showCollectionView();
166
            showInfo('Login successful.');
167
        }
168
    }
169
    //-------------------
170
    function register() {
171
        event.preventDefault();
172
        let username = $('#formRegister input[name=username]').val();
173
        let password = $('#formRegister input[name=passwd]').val();
174
        KinveyRequester.registerUser(username, password)
175
            .then(registerSuccess)
176
            .catch(handleAjaxError);
177
178
        function registerSuccess(userInfo) {
179
            saveAuthInSession(userInfo);
180
            showHideMenuLinks();
181
            showCollectionView();
182
            showInfo('User registration successful.');
183
        }
184
    }
185
    //------------------
186
    function create() {
187
        let title = $('#formCreateAd input[name=title]').val();
188
        let body = $('#formCreateAd textarea[name=description]').val();
189
        let author = sessionStorage.username;
190
        let date = $('#formCreateAd input[name=datePublished]').val();
191
        KinveyRequester.createEntity(title, body, author, date)
192
            .then(createEntitySuccess)
193
            .catch(handleAjaxError);
194
        function createEntitySuccess() {
195
            showCollectionView();
196
            showInfo('Entity created.');
197
        }
198
    }
199
    //-----------------
200
    function edit() {
201
        let entity = $('#formEditAd input[name=id]').val();
202
        console.log(entity);
203
        let title = $('#formEditAd input[name=title]').val();
204
        console.log(title);
205
        let body = $('#formEditAd textarea[name=description]').val();
206
        console.log(body);
207
        let author = sessionStorage.username;
208
        let date = $('#formEditAd input[name=datePublished]').val();
209
        KinveyRequester.editEntity(entity, title, body, author, date)
210
            .then(editEntitySuccess)
211
            .catch(handleAjaxError);
212
        function editEntitySuccess() {
213
            showCollectionView();
214
            showInfo('Entity edited.');
215
        }
216
    }
217
218
    //-----Save data in sessionStorage--------------------------------------------------//
219
    function saveAuthInSession(userInfo) {
220
        let userAuth = userInfo._kmd.authtoken;
221
        sessionStorage.setItem('authToken', userAuth);
222
        let userId = userInfo._id;
223
        sessionStorage.setItem('userID', userId);
224
        let username = userInfo.username;
225
        sessionStorage.setItem('username', username);
226
        $('#loggedInUser').text("Welcome, " + username + "!");
227
        $('#loggedInUser').show();
228
    }
229
230
    //-----Error and information messages--------------------------------------------------//
231
    function showInfo(message) {
232
        $('#infoBox').text(message);
233
        $('#infoBox').show();
234
        setTimeout(function() {
235
            $('#infoBox').fadeOut();
236
        }, 3000);
237
    }
238
    function handleAjaxError(response) {
239
        let errorMsg = JSON.stringify(response);
240
        if (response.readyState === 0)
241
            errorMsg = "Cannot connect due to network error.";
242
        if (response.responseJSON &&
243
            response.responseJSON.description)
244
            errorMsg = response.responseJSON.description;
245
        showError(errorMsg);
246
    }
247
    function showError(errorMsg) {
248
        $('#errorBox').text("Error: " + errorMsg);
249
        $('#errorBox').show();
250
    }
251
}