Skip to content

Commit ea2a7a5

Browse files
John GorterJohn Gorter
John Gorter
authored and
John Gorter
committed
'testingabc'
1 parent e8c13dc commit ea2a7a5

File tree

17 files changed

+249
-59
lines changed

17 files changed

+249
-59
lines changed

_labs/Lab. 8. Persistence/.DS_Store

6 KB
Binary file not shown.

_labs/Lab. 8. Persistence/_docs/Lab. Ajax.md

+44-26
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,70 @@
11
## Lab 8. Ajax
2-
In this lab you will use AJAX calls to retrieve and store items from a webserver.
2+
In this lab you will use AJAX calls to retrieve and store votes from a webserver.
33
> duration: 30 minutes
44
5-
### Step 1. Create a setup
6-
Create a directory 'polymer_labs\ajax' and navigate into it.
7-
Install NodeJS from it's website and use npm to install lite-server globally
8-
```
9-
$ sudo npm install lite-server -g
10-
```
5+
### Step 1. Setting the state
6+
Open file 'index.html' inside your current folder. If the exercise was not successful in the last
7+
lab, you can copy and paste a version of the files from the _solution folder from the last
8+
exercise, these files can be found in './Lab. 8. Persistence/_solution/Lab. Local Storage/'.
119

12-
Install 'express' and 'body-parser' using the following command
13-
```
14-
$ npm install express body-parser
15-
```
10+
Make sure that the current setup works. Ask the instructor for help if you not have a valid setup.
1611

17-
Copy the files from the starter files from this lab, found in the directory
18-
'_starterfiles/Lab. Ajax' into your current folder and inspect the code from the file 'index.html'.
1912

20-
Start the express server using the following command in the terminal
13+
### Step 2. Add Iron-Ajax to the application
14+
Open the earlier created 'index.html' and add the following contents
15+
16+
* Copy the server.js file from the '_starterfiles' directory for this lab into the root of your
17+
current working folder.
18+
* Install express as npm package from the command prompt
2119
```
22-
node ./server.js
20+
npm install express body-parser
2321
```
2422

25-
If it started correctly, you should see the server listening on port 3001.
26-
Open a browser and navigate to http://localhost:3001/
23+
* Remove the iron-localstorage element from the page, since we are going to retrieve the data from the server.
2724

28-
Test the application, it should work, however, the data is not retrieved and stored from/to the running server.
25+
* Add two iron-ajax elements to the page, one to automatically retrieve votes from the server, and one to post
26+
votes to the server.. Give them both ids, 'getVotes' and 'postVote' respectively. Bind the body of the postVote
27+
to a local variable named 'currentvote'. The postVote should use the content-type 'application/json' as value to
28+
be able to post JSON data.
2929

30-
### Step 2. Add Iron-Ajax to the application
31-
Open the earlier created 'index.html' and add the following contents
30+
* Use methods to call the generateRequest() api to post data to the server and retrieve new data from the server.
31+
These methods should be placed in the vote method like so:
32+
```
33+
vote: function(e){
34+
this.currentvote = e.detail;
35+
this.$.postVote.generateRequest();
36+
this.$.getVotes.generateRequest();
37+
// this.push('votes', e.detail);
38+
}
39+
```
40+
41+
Start the server to run the application, but this time use the following command to start the server
42+
```
43+
node server.js
44+
```
3245

33-
* Add two iron-ajax elements to the page, one to retrieve todos from the server, and one to post
34-
todos to the server..
35-
* Use methods to call the generateRequest() api to post data to the server and retrieve new data from the server
46+
Wait for the console to print that the server is up and running.
3647

3748
> Note that when retrieving new items from the back-end, the list is repopulated but not repainted. This is
38-
> a well known issue. The workaround is to fire an 'iron-resize' from the list that needs to repaint. This
49+
> a well-known issue. The workaround is to fire an 'iron-resize' from the list that needs to repaint. This
3950
> code looks something like this: this.$.list.fire('iron-resize');
4051
4152
Reopen or refresh the index.html and if all went well, the page displays a working setup.
42-
Add a few todos and refresh the page. Are the todos persisted?
53+
Add a few votes and refresh the page. Are the votes persisted?
54+
4355
Does the ajax get call get logged in the server console?
4456
Does the ajax post call get logged in the server console?
4557

4658

59+
### Extra: Step 3. Spot the bug
60+
when there are more than 10 votes, the current winner is calculated and shown on the screen. Does this functionality
61+
still work correctly? Why not? What is wrong here? Fix it!
62+
63+
> Note: there are two bugs. Upon entry, the winner is not calculated. Upon voting, the wrong outcome is displayed.
64+
4765

4866
### Summary
49-
We've implemented ajax calls to retrieve and post todos for the todo application,
67+
We've implemented ajax calls to retrieve and post votes for the vote application,
5068
in the next lab, we will use other storage options.
5169

5270
-= End of lab =-
10 KB
Binary file not shown.
Binary file not shown.

_labs/Lab. 8. Persistence/_solution/Lab. Ajax/index.html

+19-18
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
<link rel="import" href="/bower_components/neon-animation/neon-animation.html"/>
88
<link rel="import" href="/bower_components/neon-animation/neon-animated-pages.html"/>
99
<link rel="import" href="/bower_components/platinum-sw/platinum-sw-elements.html"/>
10-
<link rel="manifest" href="./manifest.json">
10+
<link rel="manifest" href="/manifest.json">
1111
</head>
1212
<body class="fullbleed layout vertical">
1313
<dom-module is="dom-bind" id="my-app">
@@ -23,20 +23,30 @@
2323
</neon-animated-pages>
2424
</paper-header-panel>
2525

26-
<platinum-sw-register skip-waiting clients-claim reload-on-install auto-register>
27-
<platinum-sw-cache default-cache-strategy="networkFirst"></platinum-sw-cache>
28-
</platinum-sw-register>
2926

30-
<iron-localstorage name="votes" value="{{votes}}" on-iron-localstorage-load-empty="initializeVotes"></iron-localstorage>
27+
<iron-ajax id="getVotes" auto url="/data/votes" handle-as="json" last-response="{{votes}}"></iron-ajax>
28+
<iron-ajax id="postVote" url="/data/vote" method="POST" content-type="application/json" body="[[currentvote]]"></iron-ajax>
3129

3230
</template>
3331
<script>
32+
var Candidate = function(name, lastname){
33+
this.name = name;
34+
this.lastname = lastname; }
35+
var Vote = function(candidate, time){
36+
this.candidate = candidate;
37+
this.created = Date.now();
38+
this.time = time; }
39+
3440
Polymer({
3541
is:'my-app',
3642
properties:{
3743
view:{
3844
type:String,
3945
value:'vote'
46+
},
47+
candidates:{
48+
Type:Array,
49+
value:[ new Candidate('Donald', 'Dump'), new Candidate('Hilary', 'Reagan') ]
4050
}
4151
},
4252
observers: ['_routeChanged(routeData.view)'],
@@ -55,7 +65,10 @@
5565
this.set('route.path',"/details/" + this.candidates.indexOf(item.detail));
5666
},
5767
vote: function(e){
58-
this.push('votes', e.detail);
68+
this.currentvote = e.detail;
69+
this.$.postVote.generateRequest();
70+
this.$.getVotes.generateRequest();
71+
// this.push('votes', e.detail);
5972
}
6073
});
6174
</script>
@@ -64,19 +77,7 @@
6477
<my-app></my-app>
6578

6679
<script>
67-
var Candidate = function(name, lastname){
68-
this.name = name;
69-
this.lastname = lastname; }
70-
var Vote = function(candidate, time){
71-
this.candidate = candidate;
72-
this.created = Date.now();
73-
this.time = time; }
7480
document.querySelector("my-app").message = "Election Day!";
75-
document.querySelector("my-app").candidates = [
76-
new Candidate('Donald', 'Dump'),
77-
new Candidate('Hilary', 'Reagan') ];
78-
//document.querySelector("my-app").votes = [];
7981
</script>
80-
8182
</body>
8283
</html>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
let portno = 3001;
2+
var express = require('express');
3+
var bodyParser = require('body-parser');
4+
var fs = require('fs');
5+
var app = express();
6+
7+
arrVotes = [];
8+
9+
app.use(express.static('.'));
10+
app.use(bodyParser.json())
11+
12+
13+
app.get('/vote', function(req, res){
14+
fs.readFile('./index.html', function(error, content) {
15+
res.writeHead(200, { 'Content-Type': 'text/html' });
16+
res.end(content, 'utf-8');
17+
});
18+
});
19+
20+
app.get('/details/*', function(req, res){
21+
fs.readFile('./index.html', function(error, content) {
22+
res.writeHead(200, { 'Content-Type': 'text/html' });
23+
res.end(content, 'utf-8');
24+
});
25+
});
26+
27+
28+
app.get('/data/votes', function(req, res){
29+
console.log(`returning all votes`);
30+
res.end(JSON.stringify(arrVotes));
31+
});
32+
app.post('/data/vote', function(req, res){
33+
var object = req.body;
34+
console.log(`adding a new vote to the list ${object}`, object);
35+
arrVotes.push(object);
36+
res.end();
37+
});
38+
39+
app.listen(portno, function(){
40+
console.log(`server listening on port ${portno}`);
41+
});

_labs/Lab. 8. Persistence/_solution/Lab. Ajax/vote-page.html

+11-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
<dom-module id="vote-page">
22
<template>
3-
<div name="vote"><strong>Candidates:</strong>
3+
<div name="vote"><strong>
44
<iron-list grid items="[[candidates]]" id="candidateGrid">
55
<template>
6+
67
<paper-card heading="Vote for" style="margin-top:2px;zoom:96%;width:45%;">
78
<div class="card-content"> [[item.name]] [[item.lastname]] </div>
89
<div class="card-actions">
@@ -37,21 +38,28 @@
3738
behaviors: [ Polymer.NeonAnimationRunnerBehavior ],
3839
_getSort: function(a, b){ return b.created - a.created; },
3940
getWinner: function(){
41+
if (this.votes && this.votes.length > 10){
4042
var filtered = this.votes.filter(function(item){
41-
return item.candidate === this.candidates[0];
43+
return item.candidate.name === this.candidates[0].name;
4244
}.bind(this));
4345
if (filtered.length == this.votes.length/2) return 'not defined, we need one more vote';
4446
if (filtered.length < this.votes.length/2) return this.candidates[1].name;
4547
return this.candidates[0].name;
48+
}
49+
return "";
4650
},
4751
vote: function(){
48-
if (this.votes.length > 10) this.winner = this.getWinner();
52+
this.winner = this.getWinner();
4953
this.fire('vote', new Vote(event.model.item, new Date().toLocaleTimeString()));
5054
this.playAnimation('vote');
5155
},
5256
showInfo: function(){
5357
this.fire('show-info', event.model.item);
5458
this.playAnimation('vote');
59+
},
60+
ready: function(){
61+
this.winner = this.getWinner();
62+
this.$.candidateGrid.fire('iron-resize');
5563
}
5664
});
5765
</script>
Binary file not shown.

_labs/Lab. 8. Persistence/_starterfiles/Lab. Ajax/server.js

+24-7
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,38 @@
11
let portno = 3001;
22
var express = require('express');
33
var bodyParser = require('body-parser');
4+
var fs = require('fs');
45
var app = express();
56

6-
arrTodos = [{title:'hond uitlaten', content:'hond goed uitlaten'}];
7+
arrVotes = [];
78

89
app.use(express.static('.'));
910
app.use(bodyParser.json())
1011

11-
app.get('/data/todos', function(req, res){
12-
console.log(`returning all todos`);
13-
res.end(JSON.stringify(arrTodos));
12+
13+
app.get('/vote', function(req, res){
14+
fs.readFile('./index.html', function(error, content) {
15+
res.writeHead(200, { 'Content-Type': 'text/html' });
16+
res.end(content, 'utf-8');
17+
});
18+
});
19+
20+
app.get('/details/*', function(req, res){
21+
fs.readFile('./index.html', function(error, content) {
22+
res.writeHead(200, { 'Content-Type': 'text/html' });
23+
res.end(content, 'utf-8');
24+
});
25+
});
26+
27+
28+
app.get('/data/votes', function(req, res){
29+
console.log(`returning all votes`);
30+
res.end(JSON.stringify(arrVotes));
1431
});
15-
app.post('/data/todo', function(req, res){
32+
app.post('/data/vote', function(req, res){
1633
var object = req.body;
17-
console.log(`adding a new todo to the list ${object}`, object);
18-
arrTodos.push(object);
34+
console.log(`adding a new vote to the list ${object}`, object);
35+
arrVotes.push(object);
1936
res.end();
2037
});
2138

_slides/Slides. 8. Persistence/intro.md

+3-5
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@
2121
Example
2222
```
2323
<paper-input value="{{idee}}"></paper-input>
24-
<app-localstorage-document key="idee" data="{{idee}}">
25-
</app-localstorage-document>
24+
<iron-localstorage name="idee" data="{{idee}}">
25+
</iron-localstorage>
2626
```
2727

2828
---
@@ -74,6 +74,7 @@ Make AJAX calls through an element, example:
7474
auto
7575
method="POST|GET"
7676
url="https://www.googleapis.com/youtube/v3/search"
77+
content-type="application/json"
7778
params='{"part":"snippet", "q":"polymer", "key": "YOUTUBE_API_KEY", "type": "video"}'
7879
handle-as="json"
7980
on-response="handleResponse"
@@ -129,6 +130,3 @@ PolymerFire
129130

130131
url: https://github.com/firebase/polymerfire
131132

132-
---
133-
### Hybrid Storage
134-
Sometimes one techni
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)