Passing stored selector to function - efficiency - jquery-selectors

I'm storing selectors in two variables. If I create them globally and use in function, duration of operation is about 0.2s
window.$my = {
nameEdit : $('#nameEdit'),
nameError : $('#nameError')
};
function Validation() {
console.profile();
var result = true;
if ($my.nameEdit.val() == '') {
$my.nameEdit.addClass('error');
$my.nameError.css({ 'display': 'block' });
}
else {
$my.nameEdit.removeClass('error');
$my.nameError.css({'display':'none'});
}
console.profileEnd();
}
If I'm binding another function in Validaton() and try to use them i this function, it takes too long (about 0.6s):
window.$my = {
nameEdit : $('#nameEdit'),
nameError : $('#nameError')
};
function Validation() {
$my.nameEdit.blur(function (evt) { ValidateName(evt); });
}
function ValidateName(evt) {
console.profile();
if ($my.nameEdit.val() == '') {
$my.nameEdit.addClass('error');
$my.nameError.css({ 'display': 'block' });
}
else {
$my.nameEdit.removeClass('error');
$my.nameError.css({'display':'none'});
}
console.profileEnd();
}

Related

If use async/await, it transpiles code above my "imports" and makes my func undefined

I currently have this code:
// Imports
const {utils: Cu, Constructor: CC} = Components;
Cu.import('resource://gre/modules/Services.jsm');
Services.scriptloader.loadSubScript('chrome://trigger/content/webextension/scripts/3rd/polyfill.min.js');
function install() {}
function uninstall() {}
function shutdown() {}
function startup() { // this gets automatically called by the environment i am designing for
Services.prompt.alert(Services.wm.getMostRecentWindow('navigator:browser'), 'title', 'body');
}
async function doAsync() {
return await new Promise(() => setTimeout(()=>resolve('done'), 5000));
}
However after compiling with babel with this .babelrc:
{
"presets": ["es2015", "es2017"],
"plugins": ["transform-object-rest-spread"],
"ignore": [
"3rd/**/*",
]
}
It moves my doAsync function to the top. Before the imports. Which is a problem. Because the import needs to happen right away. As startup gets called right away.
The compiled code becomes this:
'use strict';
var doAsync = function () {
var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee() {
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return new Promise(function () {
return setTimeout(function () {
return resolve('done');
}, 5000);
});
case 2:
return _context.abrupt('return', _context.sent);
case 3:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function doAsync() {
return _ref.apply(this, arguments);
};
}();
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
// Imports
var _Components = Components,
Cu = _Components.utils,
CC = _Components.Constructor;
Cu.import('resource://gre/modules/Services.jsm');
Services.scriptloader.loadSubScript('chrome://trigger/content/webextension/scripts/3rd/polyfill.min.js');
function install() {}
function uninstall() {}
function shutdown() {}
function startup() {
// this gets automatically called by the environment i am designing for Services.prompt.alert(Services.wm.getMostRecentWindow('navigator:browser'), 'title', 'body');
}
Is there anyway so that if I use async/await that it doesn't move stuff to above my imports? If my imports at the top of the file, it fails to run. Because the imports brings in the polyfill.min.js

UI5 Messagebox synchron

Hi i implemented a Messagebox in a for loop, but i know the messagebox works asynchron.
I want that the programm wait for every loop to the desicion of the user.
onBook: function(oEvent) {
var that = this;
for (var i = 0; i < Items.length; i++){
function message(innerArg) {
sap.m.MessageBox.confirm(
"Text", {
icon : sap.m.MessageBox.Icon.INFORMATION,
title : "Really",
actions : [ sap.m.MessageBox.Action.YES,
sap.m.MessageBox.Action.NO ],
onClose : function(oAction) {
if (oAction === sap.m.MessageBox.Action.NO) {
delete(i);
}else{
}
}
});
}
message(i);
}
that.do(oEvent);
The programm jumps in the "do" method before a user action is done
Edit:
for (var i = 0; i < Items.length; i++){
(function (innerArg) {
sap.m.MessageBox.confirm(
"Delete?", {
icon : sap.m.MessageBox.Icon.INFORMATION,
title : "Delete",
actions : [ sap.m.MessageBox.Action.YES,
sap.m.MessageBox.Action.NO ],
onClose : function(oAction) {
if (oAction === sap.m.MessageBox.Action.NO) {
delete(innerArg)
}}
});
})(i);
}
that.Save(oEvent);
When the box is open the entries are booked because the programm goes to the save method without wating of user action Whats wrong ?
Ah, the asynchronous-function-in-a-synchronous-loop anti-pattern ;-)
You can try using closures:
for (var i = 0; i < items; i++) {
// use self-executing function here
(function(innerArg) {
sap.m.MessageBox.confirm(
"Text", {
onClose: function(oAction) {
if (oAction === sap.m.MessageBox.Action.NO) {
// here I want to do something
console.log("Value: ", innerArg);
}
}
}
);
})(i);
}
EDIT: Update with Promises
Based on your updated question, I have provided a more-or-less sorta-kinda working example (it may not work flawless, but it should show the design pattern you should follow)
You wrap the message box responses into a Promise resolve, and store these into an array. You then feed that array to Promise.all() in order to proceed with your save functionality
processData: function() {
var promises = [],
self = this;
for (var i = 0; i < items; i++) {
promises.push(this.doMessageboxAction(i));
}
Promise.all(promises).then(function(aData) {
aData.forEach(function(oData) {
self.save(oData);
});
}).catch(function(err) {
console.log(err);
});
}
doMessageboxAction: function(item) {
return new Promise(function(resolve, reject) {
sap.m.MessageBox.confirm(
"Text", {
onClose: function(oAction) {
if (oAction === sap.m.MessageBox.Action.NO) {
//do something
//etc
resolve(item); // or some other variable
}
else {
//do something else
//etc
resolve(item); // or some other variable
}
}
}
);
});
}

How could I use tinyMCE when editing a SlickGrid column?

I would like to use tinyMCE with a custom Slick Editor outside of the table, or inside a dialog. It's just to enable rich text editing.
Can I use this external plugin for a custom Slick Editor? I have not seen any example of usages like this.
Is there any potential problems using this two plugins at the same time (injecting conflicting HTML for example or preventing some firing events)?
Use a jquery alias "jQuery_new" with a compatible version
Register the new editor "TinyMCEEditor" & Add it into slick.editors.js
Use it like this {id: "column2", name: "Year", field: "year", editor: Slick.Editors.TinyMCE}
jQuery_new.extend(true, window, {
"Slick": {
"Editors": {
(..)
"TinyMCE": TinyMCEEditor
}
}});
function TinyMCEEditor(args) {
var $input, $wrapper;
var defaultValue;
var scope = this;
this.guid = function () {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4();
},
this.init = function () {
var $container = jQuery_new(".container");
var textAreaIdString = 'rich-editor-'+guid();
$wrapper = jQuery_new("<DIV ID='rds-wrapper'/>").appendTo($container);
$input = jQuery_new("<TEXTAREA id=" + textAreaIdString + "/>");
$input.appendTo($wrapper);
jQuery_new("#" +textAreaIdString).val( args.item[args.column.field] );
var _this = this;
tinymce.init({
selector: "#"+textAreaIdString,
forced_root_block : "",
plugins : "save image imagetools",
toolbar: 'undo redo | styleselect | bold italic | link image | save',
save_onsavecallback: function() {
jQuery_new("#" +textAreaIdString).val( this.getContent() );
_this.save();
}
});
$input.bind("keydown", this.handleKeyDown);
scope.position(args.position);
$input.focus().select();
};
this.handleKeyDown = function (e) {
if (e.which == jQuery_new.ui.keyCode.ENTER && e.ctrlKey) {
scope.save();
} else if (e.which == jQuery_new.ui.keyCode.ESCAPE) {
e.preventDefault();
scope.cancel();
} else if (e.which == jQuery_new.ui.keyCode.TAB && e.shiftKey) {
e.preventDefault();
args.grid.navigatePrev();
} else if (e.which == jQuery_new.ui.keyCode.TAB) {
e.preventDefault();
args.grid.navigateNext();
}
};
this.save = function () {
args.commitChanges();
};
this.cancel = function () {
$input.val(defaultValue);
args.cancelChanges();
};
this.hide = function () {
$wrapper.hide();
};
this.show = function () {
$wrapper.show();
};
this.position = function (position) {
};
this.destroy = function () {
$wrapper.remove();
};
this.focus = function () {
$input.focus();
};
this.loadValue = function (item) {
$input.val(defaultValue = item[args.column.field]);
$input.select();
};
this.serializeValue = function () {
return $input.val();
};
this.applyValue = function (item, state) {
item[args.column.field] = state;
};
this.isValueChanged = function () {
return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
};
this.validate = function () {
return {
valid: true,
msg: null
};
};
this.init();
}

hash format error! using routing

I have developed an OpenUI5 app ant it works fine!
But every time that I invoke the routing I have this message:
2015-07-15 16:15:45 hash format error! The current Hash: /line/01 -
log
error
onHashChange
detectHashChange
jQuery.event.dispatch
jQuery.event.add.elemData.handle
It is not a blocking problem but it is annoying because it dirty and fills thi debug console..!
To call the router I write:
this.router = sap.ui.core.UIComponent.getRouterFor(this);
this.router.navTo("activities", {
"id_line": '01'
});
and this is the routing file:
routes: [
...
{
pattern: "line/{id_line}",
name: "activities",
target: ["master_search", "detail_activities"]
},
...
],
targets: {
master_search: {
viewName: "UniversalMenu",
viewLevel: 1,
controlAggregation: "masterPages"
}
,
detail_activities: {
viewName: "DetailActivity",
viewLevel: 4
}
...
}
Edit: this is a snippet where I use jQuery.sap.history
jQuery.sap.require("jquery.sap.history");
jQuery.sap.require("sap.m.InstanceManager");
sap.ui.controller("ui5bp.view.App", {
getDefaultPage : function () {
return "Menu";
},
onInit : function () {
var historyDefaultHandler = function (navType) {
if (navType === jQuery.sap.history.NavType.Back) {
//this.navBack(this.getDefaultPage());
} else {
this.navTo(this.getDefaultPage(), null, false);
}
};
var historyPageHandler = function (params, navType) {
if (!params || !params.id) {
jQuery.sap.log.error("invalid parameter: " + params);
} else {
if (navType === jQuery.sap.history.NavType.Back) {
this.navBack(params.id);
} else {
this.navTo(params.id, params.data, false);
}
}
};
jQuery.sap.history({
routes: [{
// This handler is executed when you navigate back to the history state on the path "page"
path : "page",
handler : jQuery.proxy(historyPageHandler, this)
}],
// The default handler is executed when you navigate back to the history state with an empty hash
defaultHandler: jQuery.proxy(historyDefaultHandler, this)
});
// subscribe to event bus
var bus = sap.ui.getCore().getEventBus();
bus.subscribe("nav", "to", this.navHandler, this);
bus.subscribe("nav", "back", this.navHandler, this);
bus.subscribe("nav", "virtual", this.navHandler, this);
},
navHandler: function (channelId, eventId, data) {
if (eventId === "to") {
this.navTo(data.id, data.data, true);
} else if (eventId === "back") {
//**************************************************
// if(data && data.id){
// this.navBack(data.id);
// } else {
// jQuery.sap.history.back();
// }
var app = this.getView().app;
if(data.type==="master"){
app.backMaster();
}else if(data.type==="detail"){
app.backDetail();
}else{alert("back to master o detail?");};
//**************************************************
} else if (eventId === "virtual") {
jQuery.sap.history.addVirtualHistory();
} else {
jQuery.sap.log.error("'nav' event cannot be processed. There's no handler registered for event with id: " + eventId);
}
},
navTo : function (id, data, writeHistory) {
if (id === undefined) {
// invalid parameter
jQuery.sap.log.error("navTo failed due to missing id");
} else {
var app = this.getView().app;
// navigate in the app control
app.to(id, "slide", data);
}
},
/*
navBack : function (id) {
if (!id) {
// invalid parameter
jQuery.sap.log.error("navBack - parameters id must be given");
} else {
// close open popovers
if (sap.m.InstanceManager.hasOpenPopover()) {
sap.m.InstanceManager.closeAllPopovers();
}
// close open dialogs
if (sap.m.InstanceManager.hasOpenDialog()) {
sap.m.InstanceManager.closeAllDialogs();
jQuery.sap.log.info("navBack - closed dialog(s)");
}
// ... and navigate back
var app = this.getView().app;
var currentId = (app.getCurrentPage()) ? app.getCurrentPage().getId() : null;
if (currentId !== id) {
app.backToPage(id);
jQuery.sap.log.info("navBack - back to page: " + id);
}
}
}
*/
});
In Component.js I had 2 rows where I set up custom myNavBack and myNavToWithoutHash functions:
// 3a. monkey patch the router
var oRouter = this.getRouter();
oRouter.myNavBack = ui5bp.MyRouter.myNavBack; //to comment
oRouter.myNavToWithoutHash = ui5bp.MyRouter.myNavToWithoutHash; //to comment
I have started from an example of app skeleton for my app and then I have implemented the routing with the logic suggested from the framework.
This coexistence of two different methods to navigate produced the error in console. Tahnkyou #TimGerlach
After the comment of the two rows errors have vanished.

How to reuse jquery-ui-autocomplete cached results when appending search term?

I have the following JS method to bind the jQuery UI autocomplete widget to a search text box. Everything works fine, including caching, except that I make unnecessary server calls when appending my search term because I don't reuse the just-retrieved results.
For example, searching for "ab" fetches some results from the server. Typing "c" after "ab" in the search box fetches "abc" results from the server, instead of reusing the cached "ab" results and omitting ones that don't match "abc".
I went down the path of manually looking up the "ab" search results, filtering them using a regex to select the "abc" subset, but this totally seems like I'm reinventing the wheel. What is the proper, canonical way to tell the widget to use the "ab" results, but filter them for the "abc" term and redisplay the shortened dropdown?
function bindSearchForm() {
"use strict";
var cache = new Object();
$('#search_text_field').autocomplete({
minLength: 2,
source: function (request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
$.ajax({type: 'POST',
dataType: 'json',
url: '/get_search_data',
data: {q: term},
success: function (data) {
cache[term] = data;
response(data);
}
});
});
}
Here's my "brute-force, reinventing the wheel" method, which is, for now, looking like the right solution.
function bindSearchForm() {
"use strict";
var cache = new Object();
var terms = new Array();
function cacheNewTerm(newTerm, results) {
// maintain a 10-term cache
if (terms.push(newTerm) > 10) {
delete cache[terms.shift()];
}
cache[newTerm] = results;
};
$('#search_text_field').autocomplete({
minLength: 2,
source: function (request, response) {
var term = request.term.toLowerCase();
if (term in cache) {
response(cache[term]);
return;
} else if (terms.length) {
var lastTerm = terms[terms.length - 1];
if (term.substring(0, lastTerm.length) === lastTerm) {
var results = new Array();
for (var i = 0; i < cache[lastTerm].length; i++) {
if (cache[lastTerm][i].label.toLowerCase().indexOf(term) !== -1) {
results.push(cache[lastTerm][i]);
}
}
response(results);
return;
}
}
$.ajax({type: 'POST',
dataType: 'json',
url: '/get_search_data',
data: {q: term},
success: function (data) {
cacheNewTerm(term, data);
response(data);
return;
}
});
});
}
If anyone wants a version that supports multiple entries in the text box then please see below:
$(function () {
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
var cache = new Object();
var terms = new Array();
function cacheNewTerm(newTerm, results) {
// keep cache of 10 terms
if (terms.push(newTerm) > 10) {
delete cache[terms.shift()];
}
cache[newTerm] = results;
}
$("#searchTextField")
.on("keydown",
function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).autocomplete("instance").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 2,
source: function (request, response) {
var term = extractLast(request.term.toLowerCase());
if (term in cache) {
response(cache[term]);
return;
} else if (terms.length) {
var lastTerm = terms[terms.length - 1];
console.log('LAst Term: ' + lastTerm);
if (term.substring(0, lastTerm.length) === lastTerm) {
var results = new Array();
for (var i = 0; i < cache[lastTerm].length; i++) {
console.log('Total cache[lastTerm[.length] = ' +
cache[lastTerm].length +
'....' +
i +
'-' +
lastTerm[i]);
console.log('Label-' + cache[lastTerm][i]);
var cachedItem = cache[lastTerm][i];
if (cachedItem != null) {
if (cachedItem.toLowerCase().indexOf(term) !== -1) {
results.push(cache[lastTerm][i]);
}
}
}
response(results);
return;
}
}
$.ajax({
url: '#Url.Action("GetSearchData", "Home")',
dataType: "json",
contentType: 'application/json, charset=utf-8',
data: {
term: extractLast(request.term)
},
success: function (data) {
cacheNewTerm(term, data);
response($.map(data,
function (item) {
return {
label: item
};
}));
},
error: function (xhr, status, error) {
alert(error);
}
});
},
search: function () {
var term = extractLast(this.value);
if (term.length < 2) {
return false;
}
},
focus: function () {
return false;
},
select: function (event, ui) {
var terms = split(this.value);
terms.pop();
terms.push(ui.item.value);
terms.push("");
this.value = terms.join(", ");
return false;
}
});