HTML and CSS Reference
In-Depth Information
In order to visualize this message in our application, we need to write the Javascript to connect to pusher,
subscribe to a channel, and bind to an event.
Our htML file included a script called init.js . so let's create that file in a directory called scripts. Inside,
we'll add two code blocks: one will listen for events triggered by our server-side script, and one will capture form
submissions and send them to post.php without refreshing the page. to start, let's add an event listener for
custom pusher events:
(function($){
// Handles receiving messages
var pusher = new Pusher('1507a86011e47d3d00ad'),
channel = pusher.subscribe('exercise-3-2);
// Adds an event listener for the custom event triggered by Pusher
channel
.bind(
'send-message',
function(data) {
var cont = $('#messages');
// Removes the placeholder LI if it's present
cont.find('.no-messages').remove();
// Adds the new message to the page
$('<li>')
.html('<strong>'+data.name+':</strong> '+data.msg)
.appendTo(cont);
}
);
// TODO: Handle form submission
})(jQuery);
this creates a new Pusher object using our app apI key—(again, don't forget to use your own) and then
subscribes to the channel we're using on the server side in Exercise 3-2) .
Next we bind an event handler to the channel to catch the send-message event. When it's triggered, we grab
the unordered list for message display, make sure to remove the placeholder message if it's present, and then
append the new message to the bottom of the list.
to prevent the page from reloading, which would remove any messages from our application that had been added
by Javascript from our browser, we need to add a second code block to capture form submissions and post them
via aJaX instead of using a page refresh. add this by inserting the bold code:
(function($){
// Handles receiving messages
var pusher = new Pusher('1507a86011e47d3d00ad'),
channel = pusher.subscribe('exercise-3-2);
Search WWH ::




Custom Search