Advertisement
Guest User

Untitled

a guest
Feb 20th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.66 KB | None | 0 0
  1. /**
  2. * The main application class. An instance of this class is created by app.js when it
  3. * calls Ext.application(). This is the ideal place to handle application launch and
  4. * initialization details.
  5. */
  6. Ext.define('Admin.Application', {
  7. extend: 'Ext.app.Application',
  8.  
  9. name: 'Admin',
  10.  
  11. requires: [
  12. "Admin.store.Connects",
  13. "Admin.store.Menu",
  14.  
  15. "Admin.view.main.Main"
  16. ],
  17.  
  18. defaultToken: "home",
  19.  
  20. mainView: "Admin.view.main.Main",
  21.  
  22. /**
  23. * Возвращаяет viewport.
  24. * @returns {*}
  25. */
  26. getPageMain: function () {
  27. return Ext.ComponentQuery.query("main-main")[0];
  28. },
  29.  
  30. /**
  31. * Возвращает компонет menu.
  32. * @returns {*}
  33. */
  34. getPageMenu: function () {
  35. return Ext.ComponentQuery.query("main-mainmenu")[0];
  36. },
  37.  
  38. /**
  39. * Возвращает внутренний контейнер приложения.
  40. * @returns {*}
  41. */
  42. getPageContainer: function () {
  43. return Ext.ComponentQuery.query("main-maincontainerwrap")[0];
  44. },
  45.  
  46. /**
  47. *
  48. * @returns {*}
  49. */
  50. getPageInnerContainer: function () {
  51. return Ext.ComponentQuery.query("main-maincontainer")[0];
  52. },
  53.  
  54. /**
  55. * Запуск приложения.
  56. * Проверка на авторизацию пользователя.
  57. * Загрузка всех необходимых данных для работы приложения.
  58. */
  59. launch: function () {
  60. this.loadDataApp(true).then(
  61. function () {
  62. this.setRoutesApp();
  63. this.redirectTo(Ext.util.History.getToken() || this.getDefaultToken(), true);
  64. }.bind(this),
  65. function () {
  66. this.setRoutesApp();
  67. this.redirectTo("login", true);
  68. }.bind(this)
  69. );
  70. },
  71.  
  72. /**
  73. * Загрузка меню.
  74. * Загрузка парамеров пользователя.
  75. * Использует функции {@link #this.isAuthorise}
  76. * @returns {Ext.Promise}
  77. */
  78. loadDataApp: function () {
  79. return Ext.create("Ext.Promise", function (resolve, reject) {
  80. this.isAuthorise().then(
  81. function (response) {
  82. var main = this.getPageMain();
  83. var viewModel = main.getViewModel();
  84. var storeMenu = Ext.create("Admin.store.Menu");
  85. var storeConnects = Ext.create("Admin.store.Connects");
  86. storeConnects.add(response);
  87.  
  88. storeMenu.load({
  89. callback: function () {
  90. viewModel.set({
  91. menu: storeMenu,
  92. connect: storeConnects.getAt(storeConnects.getData().length - 1)
  93. });
  94. resolve(response);
  95. }
  96. });
  97. }.bind(this),
  98. function (response) {
  99. reject(response.status);
  100. }.bind(this)
  101. );
  102. }.bind(this));
  103. },
  104.  
  105. /**
  106. * Устанавливает событие на изменения хеша в адресной строки.
  107. * Значение токена адресной строки обрабатывается функцией {@link #this.onRoute}
  108. */
  109. setRoutesApp: function () {
  110. this.setListen({
  111. controller: {
  112. '*': {
  113. unmatchedroute: 'onRoute'
  114. }
  115. }
  116. });
  117. },
  118.  
  119. /**
  120. * Разбор токена на параметра отображения модуля.
  121. * @param token
  122. * @returns {Object}
  123. */
  124. decodeToken: function (token) {
  125. var params = {};
  126. params["view"] = Ext.Array.clean(((token.split(":")[0]).split("?")[0]).split("/")).join("/");
  127. params["tab"] = (token.split(":")[1])? (token.split(":")[1]).split("?")[0]: null;
  128. params["params"] = (token.split(":")[1])? (token.split(":")[1]).split("?")[1]: token.split("?")[1];
  129. if (params["params"]) {
  130. params["params"] = Ext.Object.fromQueryString(params["params"]);
  131. }
  132.  
  133. return params;
  134. },
  135.  
  136. /**
  137. * В случае если сессия не активна то пользователя перенаправляет на страницу login {@link #this.onLogout}
  138. * @param token
  139. */
  140. onRoute: function (token) {
  141. var params = this.decodeToken(token);
  142. if (!params["view"]) {
  143. this.redirectTo(this.getDefaultToken(), true);
  144. }
  145. else if (params["view"] == "login") {
  146. this.onRedirectLogin();
  147. }
  148. else {
  149. this.isAuthorise().then(
  150. function () {
  151. this.onRouteChange(params);
  152. }.bind(this),
  153. function () {
  154. this.onLogout();
  155. }.bind(this)
  156. );
  157. }
  158.  
  159. },
  160.  
  161. /**
  162. * Проверка на авторизации сессии.
  163. * @returns {Ext.Promise}
  164. */
  165. isAuthorise: function () {
  166. return Ext.create("Ext.Promise", function (resolve, reject) {
  167. if (!Ext.util.Cookies.get("hash")) {
  168. reject({});
  169. return;
  170. }
  171. Ext.Ajax.request({
  172. scope: this,
  173. url: '/api/connects/' + Ext.util.Cookies.get("hash"),
  174. method: 'GET',
  175. success: function (response) {
  176. var parseText = Ext.JSON.decode(response.responseText, true);
  177. if (!parseText["response"]["data"]) {
  178. reject(response.status);
  179. return
  180. }
  181.  
  182. resolve(parseText["response"]["data"]);
  183. },
  184. failure: function (response) {
  185. reject(response.status);
  186. }
  187. });
  188. }.bind(this));
  189. },
  190.  
  191. /**
  192. * Проверка действия сессии. В случае если сессия не активна то переходим на страницу авторицации.
  193. */
  194. onRedirectLogin: function () {
  195. this.isAuthorise().then(
  196. function () {
  197. this.redirectTo(this.getDefaultToken());
  198. }.bind(this),
  199. function () {
  200. var container = this.getPageContainer();
  201. var main = this.getPageMain();
  202. var viewModel = main.getViewModel();
  203.  
  204. viewModel.set({
  205. menu: null,
  206. connect: null
  207. });
  208.  
  209. if (container.items.length > 0) {
  210. container.removeAll();
  211. }
  212.  
  213. Ext.util.Cookies.clear("hash");
  214.  
  215. Ext.create("Admin.view.main.MainLogin");
  216. }.bind(this)
  217. );
  218. },
  219.  
  220. /**
  221. * Создание и отображения модуля в случае если модуль был ранее создан то его просто отображаем.
  222. * Установка параметров модуля с помощью функции {@link #this.setParamsModule}.
  223. * @param params
  224. */
  225. onRouteChange: function (params) {
  226. var hash = params["view"];
  227.  
  228. hash = (hash || '').toLowerCase();
  229.  
  230. var menu = this.getPageMenu();
  231. var container = this.getPageContainer();
  232. var innerContainer = this.getPageInnerContainer();
  233. var mainCard = container.getLayout();
  234. var innerLayout = innerContainer.getLayout();
  235.  
  236. var menuStore = menu.getStore();
  237. var model = menuStore.findNode('routeId', hash);
  238. var page404 = Ext.ComponentQuery.query("main-page404")[0];
  239. var viewType = model && model.get("selectable") ? model.get("viewType") : "main-page404";
  240.  
  241. var newModule;
  242. var existModule = container.child('component[routeId=' + hash + ']');
  243. var lastModule = this.lastModule;
  244.  
  245. if (lastModule && lastModule.isWindow) {
  246. lastModule.destroy();
  247. }
  248.  
  249. lastModule = mainCard.getActiveItem();
  250.  
  251. if (viewType == "home-home") {
  252. innerLayout.setAlign("stretchmax");
  253. }
  254. else {
  255. innerLayout.setAlign("stretch");
  256. }
  257. innerContainer.updateLayout();
  258.  
  259. if (!existModule) {
  260. newModule = Ext.create({
  261. xtype: viewType,
  262. routeId: hash,
  263. hideMode: 'offsets'
  264. });
  265. }
  266.  
  267. if (!newModule || !newModule.isWindow) {
  268. if (existModule) {
  269.  
  270. this.setParamsModule(existModule, params);
  271.  
  272. if (existModule !== lastModule) {
  273. mainCard.setActiveItem(existModule);
  274. }
  275.  
  276. newModule = existModule;
  277. }
  278. else {
  279. Ext.suspendLayouts();
  280.  
  281. this.setParamsModule(newModule, params);
  282.  
  283. mainCard.setActiveItem(container.add(newModule));
  284.  
  285. Ext.resumeLayouts(true);
  286. }
  287. }
  288.  
  289. if (page404 && viewType != "main-page404") {
  290. page404.close();
  291. }
  292.  
  293. menu.setSelection(model);
  294.  
  295. if (newModule.isFocusable(true)) {
  296. newModule.focus();
  297. }
  298.  
  299. newModule.fireEvent("viewModule", params);
  300.  
  301. this.lastModule = newModule;
  302.  
  303. },
  304.  
  305. /**
  306. * Установка параметров модуля.
  307. * @param module
  308. * @param params
  309. */
  310. setParamsModule: function (module, params) {
  311. var pageView = this.getPageMain();
  312. var pageViewModel = pageView.getViewModel();
  313. var viewModel = module.getViewModel();
  314. if (!viewModel) {
  315. return;
  316. }
  317.  
  318. viewModel.set({
  319. connect: pageViewModel.get("connect"),
  320. urlParams: params
  321. });
  322.  
  323. },
  324.  
  325. /**
  326. * Диактивация сессии пользователя
  327. */
  328. onLogout: function () {
  329. var main = this.getPageMain();
  330. var hash = Ext.util.Cookies.get("hash");
  331. if (!hash) {
  332. window.location.reload();
  333. return;
  334. }
  335. main.setLoading(true);
  336. Ext.Ajax.request({
  337. scope: this,
  338. url: '/api/connects/' + Ext.util.Cookies.get("hash"),
  339. method: 'DELETE',
  340. isIgnoreError: true,
  341. success: function () {
  342. window.location.reload();
  343. },
  344. failure: function () {
  345. Ext.util.Cookies.clear("hash");
  346. window.location.reload();
  347. },
  348. callback: function () {
  349. main.setLoading(false);
  350. }
  351. });
  352. }
  353.  
  354. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement