Java Reference
In-Depth Information
});
};
The code is very simple. We just create the WebSocket object using the URL to our en-
dpoint, and then we define the onmessage function in that object. During the function
execution, the received message is automatically parsed from the JSON to JavaScript ob-
ject. Then, in $scope.$apply , we just iterate through our seats, and if the ID matches,
we update the booked state. We have to use $scope.$apply because we are touching
an Angular object from outside the Angular world (the onmessage function). Modifica-
tions performed on $scope.seats are automatically visible on the website. With this,
we can just open our ticket booking website in two browser sessions, and see that when
one user buys a ticket, the second users sees almost instantly that the seat state is changed
to booked .
We can enhance our application a little to inform users if the WebSocket connection is
really working. Let's just define onopen and onclose functions for this purpose:
ws.onopen = function (event) {
$scope.$apply(function () {
$scope.alerts.push({
type: 'info',
msg: 'Push connection from server is working'
});
});
};
ws.onclose = function (event) {
$scope.$apply(function () {
$scope.alerts.push({
type: 'warning',
msg: 'Error on push connection from server '
});
});
};
To inform users about a connection's state, we push different types of alerts. Of course,
again we're touching the Angular world from the outside, so we have to perform all opera-
tions on Angular from the $scope.$apply function.
Search WWH ::




Custom Search