Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * The main application class. An instance of this class is created by app.js when it
- * calls Ext.application(). This is the ideal place to handle application launch and
- * initialization details.
- */
- Ext.define('Admin.Application', {
- extend: 'Ext.app.Application',
- name: 'Admin',
- requires: [
- "Admin.store.Connects",
- "Admin.store.Menu",
- "Admin.view.main.Main"
- ],
- defaultToken: "home",
- mainView: "Admin.view.main.Main",
- /**
- * Возвращаяет viewport.
- * @returns {*}
- */
- getPageMain: function () {
- return Ext.ComponentQuery.query("main-main")[0];
- },
- /**
- * Возвращает компонет menu.
- * @returns {*}
- */
- getPageMenu: function () {
- return Ext.ComponentQuery.query("main-mainmenu")[0];
- },
- /**
- * Возвращает внутренний контейнер приложения.
- * @returns {*}
- */
- getPageContainer: function () {
- return Ext.ComponentQuery.query("main-maincontainerwrap")[0];
- },
- /**
- *
- * @returns {*}
- */
- getPageInnerContainer: function () {
- return Ext.ComponentQuery.query("main-maincontainer")[0];
- },
- /**
- * Запуск приложения.
- * Проверка на авторизацию пользователя.
- * Загрузка всех необходимых данных для работы приложения.
- */
- launch: function () {
- this.loadDataApp(true).then(
- function () {
- this.setRoutesApp();
- this.redirectTo(Ext.util.History.getToken() || this.getDefaultToken(), true);
- }.bind(this),
- function () {
- this.setRoutesApp();
- this.redirectTo("login", true);
- }.bind(this)
- );
- },
- /**
- * Загрузка меню.
- * Загрузка парамеров пользователя.
- * Использует функции {@link #this.isAuthorise}
- * @returns {Ext.Promise}
- */
- loadDataApp: function () {
- return Ext.create("Ext.Promise", function (resolve, reject) {
- this.isAuthorise().then(
- function (response) {
- var main = this.getPageMain();
- var viewModel = main.getViewModel();
- var storeMenu = Ext.create("Admin.store.Menu");
- var storeConnects = Ext.create("Admin.store.Connects");
- storeConnects.add(response);
- storeMenu.load({
- callback: function () {
- viewModel.set({
- menu: storeMenu,
- connect: storeConnects.getAt(storeConnects.getData().length - 1)
- });
- resolve(response);
- }
- });
- }.bind(this),
- function (response) {
- reject(response.status);
- }.bind(this)
- );
- }.bind(this));
- },
- /**
- * Устанавливает событие на изменения хеша в адресной строки.
- * Значение токена адресной строки обрабатывается функцией {@link #this.onRoute}
- */
- setRoutesApp: function () {
- this.setListen({
- controller: {
- '*': {
- unmatchedroute: 'onRoute'
- }
- }
- });
- },
- /**
- * Разбор токена на параметра отображения модуля.
- * @param token
- * @returns {Object}
- */
- decodeToken: function (token) {
- var params = {};
- params["view"] = Ext.Array.clean(((token.split(":")[0]).split("?")[0]).split("/")).join("/");
- params["tab"] = (token.split(":")[1])? (token.split(":")[1]).split("?")[0]: null;
- params["params"] = (token.split(":")[1])? (token.split(":")[1]).split("?")[1]: token.split("?")[1];
- if (params["params"]) {
- params["params"] = Ext.Object.fromQueryString(params["params"]);
- }
- return params;
- },
- /**
- * В случае если сессия не активна то пользователя перенаправляет на страницу login {@link #this.onLogout}
- * @param token
- */
- onRoute: function (token) {
- var params = this.decodeToken(token);
- if (!params["view"]) {
- this.redirectTo(this.getDefaultToken(), true);
- }
- else if (params["view"] == "login") {
- this.onRedirectLogin();
- }
- else {
- this.isAuthorise().then(
- function () {
- this.onRouteChange(params);
- }.bind(this),
- function () {
- this.onLogout();
- }.bind(this)
- );
- }
- },
- /**
- * Проверка на авторизации сессии.
- * @returns {Ext.Promise}
- */
- isAuthorise: function () {
- return Ext.create("Ext.Promise", function (resolve, reject) {
- if (!Ext.util.Cookies.get("hash")) {
- reject({});
- return;
- }
- Ext.Ajax.request({
- scope: this,
- url: '/api/connects/' + Ext.util.Cookies.get("hash"),
- method: 'GET',
- success: function (response) {
- var parseText = Ext.JSON.decode(response.responseText, true);
- if (!parseText["response"]["data"]) {
- reject(response.status);
- return
- }
- resolve(parseText["response"]["data"]);
- },
- failure: function (response) {
- reject(response.status);
- }
- });
- }.bind(this));
- },
- /**
- * Проверка действия сессии. В случае если сессия не активна то переходим на страницу авторицации.
- */
- onRedirectLogin: function () {
- this.isAuthorise().then(
- function () {
- this.redirectTo(this.getDefaultToken());
- }.bind(this),
- function () {
- var container = this.getPageContainer();
- var main = this.getPageMain();
- var viewModel = main.getViewModel();
- viewModel.set({
- menu: null,
- connect: null
- });
- if (container.items.length > 0) {
- container.removeAll();
- }
- Ext.util.Cookies.clear("hash");
- Ext.create("Admin.view.main.MainLogin");
- }.bind(this)
- );
- },
- /**
- * Создание и отображения модуля в случае если модуль был ранее создан то его просто отображаем.
- * Установка параметров модуля с помощью функции {@link #this.setParamsModule}.
- * @param params
- */
- onRouteChange: function (params) {
- var hash = params["view"];
- hash = (hash || '').toLowerCase();
- var menu = this.getPageMenu();
- var container = this.getPageContainer();
- var innerContainer = this.getPageInnerContainer();
- var mainCard = container.getLayout();
- var innerLayout = innerContainer.getLayout();
- var menuStore = menu.getStore();
- var model = menuStore.findNode('routeId', hash);
- var page404 = Ext.ComponentQuery.query("main-page404")[0];
- var viewType = model && model.get("selectable") ? model.get("viewType") : "main-page404";
- var newModule;
- var existModule = container.child('component[routeId=' + hash + ']');
- var lastModule = this.lastModule;
- if (lastModule && lastModule.isWindow) {
- lastModule.destroy();
- }
- lastModule = mainCard.getActiveItem();
- if (viewType == "home-home") {
- innerLayout.setAlign("stretchmax");
- }
- else {
- innerLayout.setAlign("stretch");
- }
- innerContainer.updateLayout();
- if (!existModule) {
- newModule = Ext.create({
- xtype: viewType,
- routeId: hash,
- hideMode: 'offsets'
- });
- }
- if (!newModule || !newModule.isWindow) {
- if (existModule) {
- this.setParamsModule(existModule, params);
- if (existModule !== lastModule) {
- mainCard.setActiveItem(existModule);
- }
- newModule = existModule;
- }
- else {
- Ext.suspendLayouts();
- this.setParamsModule(newModule, params);
- mainCard.setActiveItem(container.add(newModule));
- Ext.resumeLayouts(true);
- }
- }
- if (page404 && viewType != "main-page404") {
- page404.close();
- }
- menu.setSelection(model);
- if (newModule.isFocusable(true)) {
- newModule.focus();
- }
- newModule.fireEvent("viewModule", params);
- this.lastModule = newModule;
- },
- /**
- * Установка параметров модуля.
- * @param module
- * @param params
- */
- setParamsModule: function (module, params) {
- var pageView = this.getPageMain();
- var pageViewModel = pageView.getViewModel();
- var viewModel = module.getViewModel();
- if (!viewModel) {
- return;
- }
- viewModel.set({
- connect: pageViewModel.get("connect"),
- urlParams: params
- });
- },
- /**
- * Диактивация сессии пользователя
- */
- onLogout: function () {
- var main = this.getPageMain();
- var hash = Ext.util.Cookies.get("hash");
- if (!hash) {
- window.location.reload();
- return;
- }
- main.setLoading(true);
- Ext.Ajax.request({
- scope: this,
- url: '/api/connects/' + Ext.util.Cookies.get("hash"),
- method: 'DELETE',
- isIgnoreError: true,
- success: function () {
- window.location.reload();
- },
- failure: function () {
- Ext.util.Cookies.clear("hash");
- window.location.reload();
- },
- callback: function () {
- main.setLoading(false);
- }
- });
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement