Skip to content

Instantly share code, notes, and snippets.

@linusthe3rd
Last active January 13, 2016 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save linusthe3rd/ae41e2742231579ad4e7 to your computer and use it in GitHub Desktop.
Save linusthe3rd/ae41e2742231579ad4e7 to your computer and use it in GitHub Desktop.
// ...other instantiation logic...
var userID = getIDFromPageURI();
var user = null;
var loadUser = function (id) {
// GET the latest state of the user from the backend
$.get("/api/user" + id)
.done(function (response) {
if (!user) {
// if the user variable is NOT defined yet, create a new instance of a UserModel.
user = new UserModel(response);
} else {
// If the user variable IS defined, fill in missing data
UserModel.fill(user, response);
}
});
}
var subscribeToNotifications = function(id) {
// only subscribe to notifications if we have a web socket open
if (notifications.isConnected()) {
notifications.subscribe("users."+id, onNotification)
.done(function () {
loadUser(id);
});
}
}
var onNotification = function (data) {
if (!user) {
// If the user variable is NOT defined, create a new instance of the user model.
user = new UserModel(data);
} else {
// If the user variable IS defined, merge the new data into the existing model
UserModel.merge(user, data);
}
}
// Now that the page is defined, load the data from the backend and subscribe to notifications
loadUser(userID);
subscribeToNotifications(userID);
// ...other instantiation logic...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment