app.viewmodel.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. function AppViewModel(dataModel) {
  2. // Private state
  3. var self = this;
  4. // Private operations
  5. function cleanUpLocation() {
  6. window.location.hash = "";
  7. if (typeof history.pushState !== "undefined") {
  8. history.pushState("", document.title, location.pathname);
  9. }
  10. }
  11. // Data
  12. self.Views = {
  13. Loading: {} // Other views are added dynamically by app.addViewModel(...).
  14. };
  15. self.dataModel = dataModel;
  16. // UI state
  17. self.view = ko.observable(self.Views.Loading);
  18. self.loading = ko.computed(function () {
  19. return self.view() === self.Views.Loading;
  20. });
  21. // UI operations
  22. // Other navigateToX functions are added dynamically by app.addViewModel(...).
  23. // Other operations
  24. self.addViewModel = function (options) {
  25. var viewItem = new options.factory(self, dataModel),
  26. navigator;
  27. // Add view to AppViewModel.Views enum (for example, app.Views.Home).
  28. self.Views[options.name] = viewItem;
  29. // Add binding member to AppViewModel (for example, app.home);
  30. self[options.bindingMemberName] = ko.computed(function () {
  31. if (!dataModel.getAccessToken()) {
  32. // The following code looks for a fragment in the URL to get the access token which will be
  33. // used to call the protected Web API resource
  34. var fragment = common.getFragment();
  35. if (fragment.access_token) {
  36. // returning with access token, restore old hash, or at least hide token
  37. window.location.hash = fragment.state || '';
  38. dataModel.setAccessToken(fragment.access_token);
  39. } else {
  40. // no token - so bounce to Authorize endpoint in AccountController to sign in or register
  41. window.location = "/Account/Authorize?client_id=web&response_type=token&state=" + encodeURIComponent(window.location.hash);
  42. }
  43. }
  44. return self.Views[options.name];
  45. });
  46. if (typeof options.navigatorFactory !== "undefined") {
  47. navigator = options.navigatorFactory(self, dataModel);
  48. } else {
  49. navigator = function () {
  50. window.location.hash = options.bindingMemberName;
  51. };
  52. }
  53. // Add navigation member to AppViewModel (for example, app.NavigateToHome());
  54. self["navigateTo" + options.name] = navigator;
  55. };
  56. self.initialize = function () {
  57. Sammy().run();
  58. };
  59. }
  60. var app = new AppViewModel(new AppDataModel());