-
Notifications
You must be signed in to change notification settings - Fork 16
/
lesson3.html
375 lines (353 loc) · 15.5 KB
/
lesson3.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
<html>
<head>
<title>Messages & Models</title>
<link href="lib/bootstrap.css" rel="stylesheet" />
<link href="lib/prism.css" rel="stylesheet" />
<link href="lib/style.css" rel="stylesheet" type="text/css" media="all" />
<script src="lib/lodash.min.js"></script>
<script src="lib/conduit.min.js"></script>
<script src="lib/postal.min.js"></script>
<script src="lib/postal.request-response.min.js"></script>
<script src="lib/q.js"></script>
<script src="lib/react.js"></script>
<script src="lib/prism.js"></script>
<script src="lib/JSXTransformer.js"></script>
<script src="lib/sourceview.js"></script>
<script>
postal.configuration.promise.createDeferred = function() {
return Q.defer();
};
postal.configuration.promise.getPromise = function(dfd) {
return dfd.promise;
};
</script>
<script type="text/jsx" id="useMessageSource">
/** @jsx React.DOM */
var ChatSession = React.createClass({
getInitialState: function() {
return {
messages: this.props.messages || []
}
},
componentWillMount: function() {
this.sub = postal.subscribe({
channel: this.props.channel,
topic: "message.received",
callback: this.receiveMessage});
},
componentWillUnmount: function() {
this.sub.unsubscribe()
},
receiveMessage: function(message) {
var messages = this.state.messages;
messages.push(message);
this.setState({messages: messages})
},
renderMessage: function(message) {
return <li key={message.id}>{message.message}</li>
},
sendMessage: function(event) {
var input = this.refs.input;
postal.publish({
channel: this.props.channel,
topic: "message.send",
data: input.state.value});
input.setState({value: ""});
},
render: function() {
return <div>
<h3>Chat Connection ({this.props.channel})</h3>
<ol>
{_.map(this.state.messages, this.renderMessage)}
</ol>
<fieldset>
<input ref="input" type="text"/>
<button onClick={this.sendMessage}>Send</button>
</fieldset>
</div>;
}
});
var FuseSessionChats = function(channel1, channel2) {
function send(channel, msg) {
postal.publish({
channel: channel,
topic: "message.received",
data: {
message: msg,
id: _.uniqueId()
}
});
}
postal.subscribe({
channel: channel1,
topic: "message.send",
callback: function(data) {
send(channel2, "["+channel1+"]:"+data);
}
});
postal.subscribe({
channel: channel2,
topic: "message.send",
callback: function(data) {
send(channel1, "["+channel2+"]:"+data);
}
});
send(channel1, "[Client] Connection established");
send(channel2, "[Client] Connection established");
};
React.renderComponent(
<div>
<ChatSession channel="chat1"/>
<ChatSession channel="chat2"/>
</div>,
document.getElementById('useMessage')
);
FuseSessionChats("chat1", "chat2")
</script>
<script type="text/jsx" id="playlistSource">
/** @jsx React.DOM */
var SongController = function(channel) {
//defines actions that can be done on our Song model/collection
//connects those actions to a postal.js channel
//initial data
var songs = {"pf": {title: 'Another Brick in the Wall', album: 'The Wall', artist: 'Pink Floyd', _id:"pf"}};
function notifyDetail(song) {
channel.publish("instance."+song._id, song);
}
function notifyList() {
channel.publish("list", _.values(songs));
}
//actual operations
function create(data, envelope) {
data = data ? data : {};
data._id = _.uniqueId();
songs[data._id] = data;
notifyDetail(data)
notifyList()
}
function update(data, envelope) {
var songId = envelope.topic.substr(7);
data._id = songId;
songs[songId] = data;
notifyDetail(data);
notifyList()
}
function patch(data, envelope) {
var songId = envelope.topic.substr(6);
var song = songs[songId];
song = _.merge(song, data, {_id: songId});
notifyDetail(song)
notifyList()
}
function remove(data, envelope) {
}
//respond to CRUD operations
channel.subscribe("create", create);
channel.subscribe("update.#", update);
channel.subscribe("patch.#", patch);
channel.subscribe("delete.#", remove);
//respond to data requests
channel.subscribe("list.get", function(data, envelope) {
envelope.reply(_.values(songs));
});
};
var SubscriptionMixin = {
/*
* Tracks subscriptions and closes them on unmount
*/
subscribe: function(channel, topic, f) {
//opens a guarded subscription. Return false to stop getting messages.
var sub;
function callback(data, envelope) {
try {
if (f(data, envelope) === false) sub.unsubscribe();
} catch (e) {
console.log("Error in subscription handler", channel, topic, f, e)
console.log(e.stack)
}
}
sub = channel.subscribe(topic, callback);
this.registerSubscription(sub)
},
registerSubscription: function(sub) {
if (!this.subscriptions) this.subscriptions = [];
this.subscriptions.push(sub)
},
componentWillUnmount: function() {
_.each(this.subscriptions, function(sub) {
sub.unsubscribe()
});
this.subscriptions = [];
}
};
var SongEntry = React.createClass({
mixins: [SubscriptionMixin],
getInitialState: function() {
return {song: this.props.song}
},
componentWillMount: function() {
//listen for updates on our song
this.subscribe(this.props.songChannel, "instance."+this.state.song._id, this.updateSong)
},
updateSong: function(data, envelope) {
this.setState({song: data})
},
update: function(refName, event) {
var patch = {};
patch[refName] = event.target.value;
this.props.songChannel.publish("patch."+this.state.song._id, patch);
},
render: function() {
return (<div>
<fieldset>
<label>Title</label>
<input value={this.state.song.title} ref="title" onChange={this.update.bind(this, "title")} type="text"/>
</fieldset>
<fieldset>
<label>Album</label>
<input value={this.state.song.album} ref="album" onChange={this.update.bind(this, "album")} type="text"/>
</fieldset>
<fieldset>
<label>Artist</label>
<input value={this.state.song.artist} ref="artist" onChange={this.update.bind(this, "artist")} type="text"/>
</fieldset>
</div>)
}
});
var SongPlayer = React.createClass({
//"plays" through our list of songs
getInitialState: function() {
return {
current_song: null
}
},
componentWillMount: function() {
this.playNext();
},
playNext: function() {
//find the next song to play and update our state
var index = _.findIndex(this.props.songs, {_id: this.state.current_song});
index += 1;
if (index >= this.props.songs.length) index = 0;
var song = this.props.songs[index]
if (song) {
this.setState({current_song: song._id});
}
//schedule this function when the song "ends"
_.delay(this.playNext.bind(this, null), 3000);
},
render: function() {
var song = _.find(this.props.songs, {_id: this.state.current_song});
return <div>
<span key="nowplaying">Now Playing: </span>
{song ? <span key="display">{song.title} - {song.album}</span> : null}
</div>
}
});
var Playlist = React.createClass({
mixins: [SubscriptionMixin],
getInitialState: function() {
return {
songs: []
};
},
componentWillMount: function() {
//request the list of songs
this.props.songChannel.request({
topic: "list.get",
data: {},
timeout: 3000
}).then(this.updateSongList);
//listen for song list updates
this.subscribe(this.props.songChannel, "list", this.updateSongList);
},
updateSongList: function(data, envelope) {
this.setState({songs: data});
},
addEntry: function() {
this.props.songChannel.publish("create", {});
},
renderSongEntry: function(song) {
return <SongEntry song={song} key={song._id} songChannel={this.props.songChannel}/>
},
render: function() {
return <div>
<ul>
{this.state.songs.map(this.renderSongEntry)}
</ul>
<button className="btn btn-success" onClick={this.addEntry}>Add</button>
<SongPlayer songs={this.state.songs}/>
</div>;
}
});
var songChannel = postal.channel("mySongs")
SongController(songChannel);
React.renderComponent(
<Playlist songChannel={songChannel}/>,
document.getElementById('playlist')
);
</script>
</head>
<body>
<section class="container">
<h1>Messages</h1>
<div class="row">
<div class="col-sm-4">
<p>
Channels allow for asynchronous message passing between code routines.
In this example we are using Postal.js which is a pub/sub library.
Messages can even be sent to web workers or to an iframe.
</p>
<ul>
<li>Use channels (aka pub/sub) to send messages to other components and systems</li>
<li>Subscribe to a topic on a channel to be notified of events</li>
<li>Remember, your component is an Actor</li>
<li>Subscribe to topics in "componentWillMount"</li>
<li>Unsubscribe from topics in "componentWillUnmount"</li>
</ul>
<div class="result" id="useMessage"></div>
</div>
<div class="col-sm-8">
<div class="sourceCode" data-source="useMessageSource" data-edit="true"></div>
</div>
</div>
</section>
<section class="container">
<h1>Models</h1>
<div class="row">
<div class="col-sm-4">
<p>
If components are editing data on a server then it is recommended that you use a model layer.
React.js doesn't care what is being used for the model layer or if AJAX is directly called as long as updates are pushed through "setState".
Messages allow for all your components to be notified of model changes.
Postal.js offers promise integration and responses handling which we use for immediate data requests.
</p>
<ul>
<li>Choose your own data backend</li>
<li>Optionally define a Mixin to contain helpers for your model layer</li>
<li>Bind to your model layer using messages or callbacks in componentWillMount</li>
<li>Unbind from the model layer in the componentWillUnmount</li>
<li>Simple applications may use Ajax calls direct from the component</li>
<li>Use <a href="https://www.npmjs.org/package/backbone-react-component">backbone-react-component</a> for backbone integration</li>
<li>Facebook has their own model layer for react called <a href="https://facebook.github.io/react/docs/flux-todo-list.html">flux</a></li>
<li>Postal.js provides a <a href="https://github.com/postaljs/postal.request-response">Request-Response</a> library for putting requests over a channel</li>
</ul>
<div class="result" id="playlist"></div>
</div>
<div class="col-sm-8">
<div class="sourceCode" data-source="playlistSource" data-edit="true"></div>
</div>
</div>
</section>
<div class="footer container">
<ul class="pagination">
<li><a href="lesson2.html">«</a></li>
<li><a href="lesson1.html">Lesson 1</a></li>
<li><a href="lesson2.html">Lesson 2</a></li>
<li class="active"><a href="lesson3.html">Lesson 3</a></li>
<li><a href="lesson4.html">Lesson 4</a></li>
<li><a href="lesson4.html">»</a></li>
</ul>
</div>
</body>
</html>