How to compare two routes by hand - vue.js

How can I manually (programmatically) compare two routes and find out if they are same? (if router-link-active or router-link-exact-active would be present)
Generally i need this sort of a function
/*
#params route1, route2 : Route
*/
function isActivated(route1, route2) {
/* comparing them somehow */
return {
exactActive,
active
};
}
Use Case:
I have a NestedLink.vue component which is wrapper over router-link.
It takes to prop just as router-link (and passes it down to child router-link). If current route is active, nested links will apear nearby.
My approach:
function isActivated(route1, route2) {
if (
route1.matched.some(record =>
record.regex.test(route2.fullPath)
)
) {
return { exactActive: true };
}
return { exactActive: false };
}
It may tell when routes are exact-active but not for not-exact-active.

This is the code, used inside router-link component.
const START = '/';
const trailingSlashRE = /\/?$/;
function isObjectEqual (a, b) {
if ( a === void 0 ) a = {};
if ( b === void 0 ) b = {};
// handle null value #1566
if (!a || !b) { return a === b }
var aKeys = Object.keys(a);
var bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) {
return false
}
return aKeys.every(function (key) {
var aVal = a[key];
var bVal = b[key];
// check nested equality
if (typeof aVal === 'object' && typeof bVal === 'object') {
return isObjectEqual(aVal, bVal)
}
return String(aVal) === String(bVal)
})
}
function isSameRoute (a, b) {
if (b === START) {
return a === b
} else if (!b) {
return false
} else if (a.path && b.path) {
return (
a.path.replace(trailingSlashRE, '') === b.path.replace(trailingSlashRE, '') &&
a.hash === b.hash &&
isObjectEqual(a.query, b.query)
)
} else if (a.name && b.name) {
return (
a.name === b.name &&
a.hash === b.hash &&
isObjectEqual(a.query, b.query) &&
isObjectEqual(a.params, b.params)
)
} else {
return false
}
}
So, here's how to use it inside component:
// OR JUST A STRING '/home'
let link = { name: 'home' }
// will return true of false
let result = isSameRoute(this.$router.resolve(link).resolved, this.$route)

Related

Typewriter is not working when loaded via npm import (compiled with Babel)

I set up Typewriter on a site, it works fine when loaded via the direct src.
<script src="https://unpkg.com/typewriter-effect#2.3.1/dist/core.js"></script>
<script>
window.addEventListener('DOMContentLoaded', () => {document.getElementById('typewriter-container');
const typewriter = new Typewriter(whatever, { ... });
...
But when I do it with npm, it doesn't work.
What does "doing it with npm" mean?
Well, since loading stuff the traditional way seems to be outdated... I'm doing the same thing with npm and using the import into a file:
src/typewriter.js
import Typewriter from 'typewriter-effect/dist/core';
And then compiling this file with webpack and babel, and loading that file instead.
<script src="/my_site_stuff/dist/typewriter.js"></script>
This is the compiled file:
dist/typewriter.js
/******/ (function() { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ "./node_modules/typewriter-effect/dist/core.js":
/*!*****************************************************!*\
!*** ./node_modules/typewriter-effect/dist/core.js ***!
\*****************************************************/
/***/ (function(module, exports, __webpack_require__) {
/* module decorator */ module = __webpack_require__.nmd(module);
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;function _typeof(obj) { "#babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
!function (e, t) {
"object" == ( false ? 0 : _typeof(exports)) && "object" == ( false ? 0 : _typeof(module)) ? module.exports = t() : true ? !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (t),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : 0;
}("undefined" != typeof self ? self : this, function () {
return function () {
var e = {
75: function _(e) {
(function () {
var t, n, r, o, a, s;
"undefined" != typeof performance && null !== performance && performance.now ? e.exports = function () {
return performance.now();
} : "undefined" != typeof process && null !== process && process.hrtime ? (e.exports = function () {
return (t() - a) / 1e6;
}, n = process.hrtime, o = (t = function t() {
var e;
return 1e9 * (e = n())[0] + e[1];
})(), s = 1e9 * process.uptime(), a = o - s) : Date.now ? (e.exports = function () {
return Date.now() - r;
}, r = Date.now()) : (e.exports = function () {
return new Date().getTime() - r;
}, r = new Date().getTime());
}).call(this);
},
4087: function _(e, t, n) {
for (var r = n(75), o = "undefined" == typeof window ? n.g : window, a = ["moz", "webkit"], s = "AnimationFrame", i = o["request" + s], u = o["cancel" + s] || o["cancelRequest" + s], l = 0; !i && l < a.length; l++) {
i = o[a[l] + "Request" + s], u = o[a[l] + "Cancel" + s] || o[a[l] + "CancelRequest" + s];
}
if (!i || !u) {
var c = 0,
p = 0,
d = [];
i = function i(e) {
if (0 === d.length) {
var t = r(),
n = Math.max(0, 16.666666666666668 - (t - c));
c = n + t, setTimeout(function () {
var e = d.slice(0);
d.length = 0;
for (var t = 0; t < e.length; t++) {
if (!e[t].cancelled) try {
e[t].callback(c);
} catch (e) {
setTimeout(function () {
throw e;
}, 0);
}
}
}, Math.round(n));
}
return d.push({
handle: ++p,
callback: e,
cancelled: !1
}), p;
}, u = function u(e) {
for (var t = 0; t < d.length; t++) {
d[t].handle === e && (d[t].cancelled = !0);
}
};
}
e.exports = function (e) {
return i.call(o, e);
}, e.exports.cancel = function () {
u.apply(o, arguments);
}, e.exports.polyfill = function (e) {
e || (e = o), e.requestAnimationFrame = i, e.cancelAnimationFrame = u;
};
}
},
t = {};
function n(r) {
var o = t[r];
if (void 0 !== o) return o.exports;
var a = t[r] = {
exports: {}
};
return e[r].call(a.exports, a, a.exports, n), a.exports;
}
n.n = function (e) {
var t = e && e.__esModule ? function () {
return e.default;
} : function () {
return e;
};
return n.d(t, {
a: t
}), t;
}, n.d = function (e, t) {
for (var r in t) {
n.o(t, r) && !n.o(e, r) && Object.defineProperty(e, r, {
enumerable: !0,
get: t[r]
});
}
}, n.g = function () {
if ("object" == (typeof globalThis === "undefined" ? "undefined" : _typeof(globalThis))) return globalThis;
try {
return this || new Function("return this")();
} catch (e) {
if ("object" == (typeof window === "undefined" ? "undefined" : _typeof(window))) return window;
}
}(), n.o = function (e, t) {
return Object.prototype.hasOwnProperty.call(e, t);
};
var r = {};
return function () {
"use strict";
n.d(r, {
default: function _default() {
return S;
}
});
var e = n(4087),
t = n.n(e);
var o = function o(e) {
return new RegExp(/<[a-z][\s\S]*>/i).test(e);
},
a = function a(e) {
var t = document.createElement("div");
return t.innerHTML = e, t.childNodes;
},
s = function s(e, t) {
return Math.floor(Math.random() * (t - e + 1)) + e;
};
var i = "TYPE_CHARACTER",
u = "REMOVE_CHARACTER",
l = "REMOVE_ALL",
c = "REMOVE_LAST_VISIBLE_NODE",
p = "PAUSE_FOR",
d = "CALL_FUNCTION",
f = "ADD_HTML_TAG_ELEMENT",
v = "CHANGE_DELETE_SPEED",
h = "CHANGE_DELAY",
m = "CHANGE_CURSOR",
y = "PASTE_STRING",
g = "HTML_TAG";
function E(e, t) {
var n = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var r = Object.getOwnPropertySymbols(e);
t && (r = r.filter(function (t) {
return Object.getOwnPropertyDescriptor(e, t).enumerable;
})), n.push.apply(n, r);
}
return n;
}
function w(e) {
for (var t = 1; t < arguments.length; t++) {
var n = null != arguments[t] ? arguments[t] : {};
t % 2 ? E(Object(n), !0).forEach(function (t) {
N(e, t, n[t]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : E(Object(n)).forEach(function (t) {
Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t));
});
}
return e;
}
function T(e) {
return function (e) {
if (Array.isArray(e)) return b(e);
}(e) || function (e) {
if ("undefined" != typeof Symbol && null != e[Symbol.iterator] || null != e["##iterator"]) return Array.from(e);
}(e) || function (e, t) {
if (e) {
if ("string" == typeof e) return b(e, t);
var n = Object.prototype.toString.call(e).slice(8, -1);
return "Object" === n && e.constructor && (n = e.constructor.name), "Map" === n || "Set" === n ? Array.from(e) : "Arguments" === n || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n) ? b(e, t) : void 0;
}
}(e) || function () {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}();
}
function b(e, t) {
(null == t || t > e.length) && (t = e.length);
for (var n = 0, r = new Array(t); n < t; n++) {
r[n] = e[n];
}
return r;
}
function A(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n];
r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r);
}
}
function N(e, t, n) {
return t in e ? Object.defineProperty(e, t, {
value: n,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[t] = n, e;
}
var S = function () {
function n(r, E) {
var b = this;
if (function (e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function");
}(this, n), N(this, "state", {
cursorAnimation: null,
lastFrameTime: null,
pauseUntil: null,
eventQueue: [],
eventLoop: null,
eventLoopPaused: !1,
reverseCalledEvents: [],
calledEvents: [],
visibleNodes: [],
initialOptions: null,
elements: {
container: null,
wrapper: document.createElement("span"),
cursor: document.createElement("span")
}
}), N(this, "options", {
strings: null,
cursor: "|",
delay: "natural",
pauseFor: 1500,
deleteSpeed: "natural",
loop: !1,
autoStart: !1,
devMode: !1,
skipAddStyles: !1,
wrapperClassName: "Typewriter__wrapper",
cursorClassName: "Typewriter__cursor",
stringSplitter: null,
onCreateTextNode: null,
onRemoveNode: null
}), N(this, "setupWrapperElement", function () {
b.state.elements.container && (b.state.elements.wrapper.className = b.options.wrapperClassName, b.state.elements.cursor.className = b.options.cursorClassName, b.state.elements.cursor.innerHTML = b.options.cursor, b.state.elements.container.innerHTML = "", b.state.elements.container.appendChild(b.state.elements.wrapper), b.state.elements.container.appendChild(b.state.elements.cursor));
}), N(this, "start", function () {
return b.state.eventLoopPaused = !1, b.runEventLoop(), b;
}), N(this, "pause", function () {
return b.state.eventLoopPaused = !0, b;
}), N(this, "stop", function () {
return b.state.eventLoop && ((0, e.cancel)(b.state.eventLoop), b.state.eventLoop = null), b;
}), N(this, "pauseFor", function (e) {
return b.addEventToQueue(p, {
ms: e
}), b;
}), N(this, "typeOutAllStrings", function () {
return "string" == typeof b.options.strings ? (b.typeString(b.options.strings).pauseFor(b.options.pauseFor), b) : (b.options.strings.forEach(function (e) {
b.typeString(e).pauseFor(b.options.pauseFor).deleteAll(b.options.deleteSpeed);
}), b);
}), N(this, "typeString", function (e) {
var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : null;
if (o(e)) return b.typeOutHTMLString(e, t);
if (e) {
var n = b.options || {},
r = n.stringSplitter,
a = "function" == typeof r ? r(e) : e.split("");
b.typeCharacters(a, t);
}
return b;
}), N(this, "pasteString", function (e) {
var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : null;
return o(e) ? b.typeOutHTMLString(e, t, !0) : (e && b.addEventToQueue(y, {
character: e,
node: t
}), b);
}), N(this, "typeOutHTMLString", function (e) {
var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : null,
n = arguments.length > 2 ? arguments[2] : void 0,
r = a(e);
if (r.length > 0) for (var o = 0; o < r.length; o++) {
var s = r[o],
i = s.innerHTML;
s && 3 !== s.nodeType ? (s.innerHTML = "", b.addEventToQueue(f, {
node: s,
parentNode: t
}), n ? b.pasteString(i, s) : b.typeString(i, s)) : s.textContent && (n ? b.pasteString(s.textContent, t) : b.typeString(s.textContent, t));
}
return b;
}), n;
}();
}(), r.default;
}();
});
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ id: moduleId,
/******/ loaded: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat get default export */
/******/ !function() {
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function() { return module['default']; } :
/******/ function() { return module; };
/******/ __webpack_require__.d(getter, { a: getter });
/******/ return getter;
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/define property getters */
/******/ !function() {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = function(exports, definition) {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ !function() {
/******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
/******/ }();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ !function() {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ }();
/******/
/******/ /* webpack/runtime/node module decorator */
/******/ !function() {
/******/ __webpack_require__.nmd = function(module) {
/******/ module.paths = [];
/******/ if (!module.children) module.children = [];
/******/ return module;
/******/ };
/******/ }();
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
!function() {
"use strict";
/*!*************************************!*\
!*** ./src/js/typewriter-effect.js ***!
\*************************************/
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var typewriter_effect_dist_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! typewriter-effect/dist/core */ "./node_modules/typewriter-effect/dist/core.js");
/* harmony import */ var typewriter_effect_dist_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(typewriter_effect_dist_core__WEBPACK_IMPORTED_MODULE_0__);
}();
/******/ })()
;
//# sourceMappingURL=typeWriter.js.map
How do I know what the problem is?
Webpack encloses everything in the compiled file so nothing leaks into the global scope.
You'd have to change your src file and do:
import Typewriter from 'typewriter-effect/dist/core';
window.Typewriter = Typewriter;
Then, when using it, instead of:
const typewriter = new Typewriter(...);
Just do:
const typewriter = new window.Typewriter(...);
What we are doing here is, making it available to the global scope.

TypeError: Cannot read properties of undefined (reading 'type') at eval ... at Array.sort (<anonymous>)

I need your help with this error I am facing colleagues. I am new to vue so I am finding it quite difficult to solve the error though I what what exactly is causing the error. I am creating a datatable in vue and I am trying to achieve data sorting with this tutorial I am following but end up getting the following error:
TypeError: Cannot read properties of undefined (reading 'type')
computed: {
filteredAccommodations(){
let accommodations = this.accommodations;
if (this.search) {
accommodations = accommodations.filter((row) => {
return Object.keys(row).some((key) => {
return String(row[key]).toLowerCase().indexOf(this.search.toLowerCase()) > -1;
})
});
}
let sortKey = this.sortKey;
let order = this.sortOrders[sortKey] || 1;
if(sortKey){
accommodations = accommodations.slice().sort((a, b) => {
let index = this.getIndex(this.columns, 'name', sortKey);
a = String(a[sortKey]).toLowerCase();
b = String(b[sortKey]).toLowerCase();
if (this.columns[index].type && this.columns[index].type === 'date') {
return (a === b ? 0 : new Date(a).getTime() > new Date(b).getTime() ? 1 : -1) * order;
} else if (this.columns[index].type && this.columns[index].type === 'number') {
return (+a === +b ? 0 : +a > +b ? 1 : -1) * order;
} else {
return (a === b ? 0 : a > b ? 1 : -1) * order;
}
});
}
return accommodations;
},
paginatedAccommodations(){
return this.paginate(this.filteredAccommodations, this.length, this.pagination.currentPage);
}
},
The reason for your error is because the value of this.columns[index] is a null value ,Adding a null check in ur if loop might help you solve this but I suggest you to check for the reason of null value.
computed: {
filteredAccommodations() {
let accommodations = this.accommodations;
if (this.search) {
accommodations = accommodations.filter((row) => {
return Object.keys(row).some((key) => {
return String(row[key]).toLowerCase().indexOf(this.search.toLowerCase()) > -1;
})
});
}
let sortKey = this.sortKey;
let order = this.sortOrders[sortKey] || 1;
if (sortKey) {
accommodations = accommodations.slice().sort((a, b) => {
let index = this.getIndex(this.columns, 'name', sortKey);
a = String(a[sortKey]).toLowerCase();
b = String(b[sortKey]).toLowerCase();
if (this.columns[index] && this.columns[index].type && this.columns[index].type === 'date') {
return (a === b ? 0 : new Date(a).getTime() > new Date(b).getTime() ? 1 : -1) * order;
} else if (this.columns[index] && this.columns[index].type && this.columns[index].type === 'number') {
return (+a === +b ? 0 : +a > +b ? 1 : -1) * order;
} else {
return (a === b ? 0 : a > b ? 1 : -1) * order;
}
});
}
return accommodations;
},
paginatedAccommodations() {
return this.paginate(this.filteredAccommodations, this.length, this.pagination.currentPage);
}
},

ag grid vue grouping set columns expanded after component reload

I use ag-grid table - I am grouping the columns e.g. like:
Is it possible to set columns expanded the same way they were after components reload?
How to save how columns were expanded and then reload it?
One way is to store the ids of the nodes which are expanded (I do so in local storage as there aren't many rows in my table and I know I won't store anything confidential). Then on reload, retrieve the nodes that should be expanded and expand them:
<ag-grid-angular
(rowGroupOpened)="onRowGroupOpened()"
(gridReady)="onGridReady($event)">
</ag-grid-angular>
localStorageKey = 'storage-key-name';
onRowGroupOpened(): void {
let allExpanded = true;
const expandedNodeDetails: string[] = [];
if (this.myGrid.gridApi != null) {
this.myGrid.gridApi.forEachNode(node => {
if (node.group || (node.allChildrenCount > 0)) {
if (!this.restoringExpandedNodes) {
expandedNodeDetails.push(node.key);
}
}
});
}
if (!this.restoringExpandedNodes) {
localStorage.setItem(this.localStorageKey, JSON.stringify(expandedNodeDetails));
}
}
onGridReady(): void {
this.restoreExpandedNodes();
}
restoreExpandedNodes(): void {
const itemsInStorage = JSON.parse(localStorage.getItem(this.localStorageKey));
if ((itemsInStorage != null) && (this.myGrid != null) && (this.myGrid.gridApi != null)) {
this.restoringExpandedNodes = true;
this.myGrid.gridApi.forEachNode(node => {
if (node.group || (node.allChildrenCount > 0)) {
const expandedDetails = this.getExpandedDetails(node, null);
const index = itemsInStorage.findIndex(storageItem => storageItem === expandedDetails);
if (index !== -1) {
node.expanded = true;
} else if ((itemToSelect != null) && (node.key == itemToSelect.ItemFullName)) {
node.expanded = true;
}
}
});
this.myGrid.gridApi.onGroupExpandedOrCollapsed();
this.restoringExpandedNodes = false;
}
}
I've had to sanitise this code so please let me know if something doesn't make sense

hide index.php from ajax load search in osclass

link look like http://localhost/index.php?page=search&sOrder=dt_pub_date&iOrderType=desc&sPattern=car
// AJAX SEARCH
$('body#body-search').on('change click', '.link-check-box a, .filter-remove a, form.search-side-form input:not(.term), body#body-search #sub-nav a, #home-cat a, #sub-cat a, form.search-side-form select, .sort-it a, .user-type a,.list-grid a, .paginate a', function(event) {
var ajaxStop = false;
if(ajaxSearch == 1 && event.type != 'change') {
event.preventDefault();
}
// Disable on mobile devices when input selected from fancybox
if($(event.target).closest('.search-mobile-filter-box').length) {
if(!$(event.target).closest('#search-sort').length && !$(event.target).closest('.sub-line').length) { // it may not be required
var ajaxStop = true;
//return false;
}
}
var sidebarReload = true;
if($(this).closest('.sidebar-hooks').length || $(event.target).attr('name') == 'locUpdate') {
sidebarReload = false;
}
var sidebar = $('.filter form.search-side-form');
var ajaxSearchUrl = '';
if (event.type == 'click') {
if(typeof $(this).attr('href') !== typeof undefined && $(this).attr('href') !== false) {
ajaxSearchUrl = $(this).attr('href');
}
} else if (event.type == 'change') {
ajaxSearchUrl = baseDir + "index.php?" + sidebar.find(':input[value!=""]').serialize();
}
if(ajaxSearch == 1 && $('input[name="ajaxRun"]').val() != "1" && (ajaxSearchUrl != '#' && ajaxSearchUrl != '') && !ajaxStop) {
if(ajaxSearchUrl == $(location).attr('href')) {
return false;
}
sidebar.find('.init-search').addClass('btn-loading').addClass('disabled').attr('disabled', true);
sidebar.find('input[name="ajaxRun"]').val("1");
$('#search-items').addClass('loading');
$.ajax({
url: ajaxSearchUrl,
type: "GET",
success: function(response){
var length = response.length;
var data = $(response).contents().find('#main').html();
var bread = $(response).contents().find('ul.breadcrumb');
var filter = $(response).contents().find('.filter').html();
sidebar.find('.init-search').removeClass('btn-loading').removeClass('disabled').attr('disabled', false);
sidebar.find('input[name="ajaxRun"]').val("");
$('#main').fadeOut(0, function(){
$('#main').html(data).show(0);
$('#search-items').hide(0);
$('#search-items').removeClass('loading');
$('#search-items').show(0).css('opacity', 0).css('margin-top', '50px').css('margin-bottom', '-50px').animate( { opacity: 1, marginTop:'0', marginBottom:'0'} , 300);
});
if(sidebarReload) {
$('.filter').html(filter);
}
$('ul.breadcrumb').html(bread);

dgrid custom sort with secondary sort column

I'm currently using a custom sort function on a dgrid (pasted below). It doesn't change sorting drastically, just sorts one particular column uniquely and sorts the others case-insensitive. I'd like to add a secondary sort by a column named "scheduled" to be added to the sort when any other column is sorted. I'm just not sure how to go about it. I've seen how to override the sort to sort by two columns, but not when a custom sort is in play. The secondary sort would always be there, not matter what other column is clicked.
For reference I'm running dojo 1.10 and dgrid 1.0. Data is coming from a RequestMemory DStore and I'd really rather this sort happen on the grid rather than back at the store level. Any help would be appreciated.
currGrid.on('dgrid-sort', function (event) {
event.preventDefault();
var sort = event.sort[0];
currGrid.set('sort', function (a, b) {
if (sort.property == "thisField") {
//special sort for thisField
if (a[sort.property] !== 'undefined' && typeof a[sort.property] == "string") {
var colorA = a[sort.property].split("|");
var aValue = colorA[0].toLowerCase();
}
if (b[sort.property] !== 'undefined' && typeof b[sort.property] == "string") {
var colorB = b[sort.property].split("|");
var bValue = colorB[0].toLowerCase();
}
if (String(aValue) == String(bValue)) {
var result = 0;
} else if (dojo.string.trim(aValue) == "") {
var result = true ? 1 : -1;
} else if (dojo.string.trim(bValue) == "") {
var result = true ? -1 : 1;
} else {
var result = aValue > bValue ? 1 : -1;
}
return result * (sort.descending ? -1 : 1);
} else {
//Sort for all other fields same as always (except toLowerCase)
if (a[sort.property] !== 'undefined' && typeof a[sort.property] == "string") {
var aValue = a[sort.property].toLowerCase();
} else {
var aValue = "";
}
if (b[sort.property] !== 'undefined' && typeof b[sort.property] == "string") {
var bValue = b[sort.property].toLowerCase();
} else {
var bValue = "";
}
var result = aValue > bValue ? 1 : -1;
return result * (sort.descending ? -1 : 1);
}
});
currGrid.updateSortArrow(event.sort, true);
});
currGrid.startup();
You could do something like below.
currGrid.on('dgrid-sort', function (event) {
event.preventDefault();
var sortSet = [];
sortSet.push(event.sort[0]);
sortSet.push({property: "scheduled"});
currGrid.set('sort', function (a, b) {
var aValue, bValue, result = 0;
for(var i = 0; i < sortSet.length; i++){
var sort = sortSet[i];
if (sort.property == "thisField") {
//special sort for thisField
if (a[sort.property] !== 'undefined' && typeof a[sort.property] == "string") {
var colorA = a[sort.property].split("|");
aValue = colorA[0].toLowerCase();
}
if (b[sort.property] !== 'undefined' && typeof b[sort.property] == "string") {
var colorB = b[sort.property].split("|");
bValue = colorB[0].toLowerCase();
}
if (String(aValue) == String(bValue)) {
result = 0;
} else if (dojo.string.trim(aValue) == "") {
result = true ? 1 : -1;
} else if (dojo.string.trim(bValue) == "") {
result = true ? -1 : 1;
} else {
result = aValue > bValue ? 1 : -1;
}
return result * (sort.descending ? -1 : 1);
} else {
//Sort for all other fields same as always (except toLowerCase)
if (a[sort.property] !== 'undefined' && typeof a[sort.property] == "string") {
aValue = a[sort.property].toLowerCase();
} else {
aValue = "";
}
if (b[sort.property] !== 'undefined' && typeof b[sort.property] == "string") {
bValue = b[sort.property].toLowerCase();
} else {
bValue = "";
}
//You need this check here
if(aValue != bValue){
result = aValue > bValue ? 1 : -1;
return result * (sort.descending ? -1 : 1);
}
}
}
return 0;
});
currGrid.updateSortArrow(event.sort, true);
});
currGrid.startup();
I have some concerns about your code, the variables result, aValue and bValue are all local within the if statement and yet they are being used outside the statement. It could result in wrong results if some other variables are defined with the same name in global space. So I have modified them.
So the second section you needed to check if aValue == bValue to return 0.