How do I generalize this set of Javascript methods, including promises? - javascript

I have the following code setup to initialize a single field's autosuggest feature using jQuery and MagicSuggest. It's relatively straight forward. I have modularized a bit of it because I intend on using it to initialize other fields as well with MagicSuggest. One extraneous part is the canonical name conversion, but it's a necessary function for this particular data set I'm working with. (Problem I'm having trouble with explained below ...)
/**
* Initialize Flights From autosuggest feature
* #return {void}
*/
function initFlightsFromAutosuggest() {
// Flights From Typeahead *************************************
var msField = $('#magicsuggest.direct_flights_from');
var ms = msField.magicSuggest({
id : 'direct_flights_from',
name : 'direct_flights_from',
minChars : 1,
highlight : false,
valueField : 'id',
displayField : 'name',
placeholder : getMSPlaceholder(msField, 'City'),
resultAsString: true,
useTabKey : true,
useCommaKey : true,
useZebraStyle : true,
hideTrigger : true,
sortOrder : 'canonical_name',
maxDropHeight : 500,
data : '/api/v1/cities',
defaultValues : msField.attr('data-default').split(','),
renderer : function(data) { return convertCanonical(data.canonical_name) }
});
// Once loaded, add pre-selected values if there are any
$(ms).on('load', addDefaults(ms, msField));
}
/**
* Gets placeholder value for MagicSuggest instances
* #param {element} el DOM element
* #param {string} defaultString Default string to use
* #return {string}
*/
function getMSPlaceholder(el, defaultString) {
if (el.attr('data-default').length > 0) {
return '';
}
return defaultString;
}
/**
* Converts canonical name into city, state string (dropping country, fixing spacing)
* #param {string} canonical_name Full canonical name
* #return {string} Short name, without country
*/
function convertCanonical(canonical_name) {
if (typeof canonical_name !== 'undefined') {
canonical_name = canonical_name.replace(',United States', '');
canonical_name = canonical_name.replace(',', ', ');
return canonical_name;
}
// Not sure what to do if it's undefined
return;
}
That all said, below is what I have to do to pre-populate this one field with data previously submitted.
/**
* Adds pre-selected values (ids) loaded into the 'data-default' attribute into the input field
* #param {object} ms MagicSuggest instantiation
* #param {element} msField DOM element used by MagicSuggest
*/
function addDefaults(ms, msField) {
// Get the default attribute value as an array
var defaultIds = msField.attr('data-default').split(',');
// Setup array of requests
var requests = [];
// Push all the requests into an array
$.each(defaultIds, function(index, id) {
requests.push($.getJSON('/api/v1/cities/' + id));
});
// Create a promise, and when all the requests are done (promises fulfilled)
// Send the args (json) to the .done callback
var promise = $.when.apply($, requests).then(function () {
var args = Array.prototype.slice.call(arguments);
return args.map(function(arg) { return arg[0] });
});
// Setup the callback function for 'done'
promise.done(function(json) {
// Setup results array
var results = [];
// Got an auth error from the API, so return early. No results.
if (typeof(json[0].auth) === 'object') {
return false;
}
// For each item, add the proper structure to the results array
$.each(json, function (index, id) {
results.push({
value: json[index][0]['city']['id'],
name: json[index][0]['city']['name']
});
});
var resultPromise = $.when.apply($, results).then(function () {
var args = Array.prototype.slice.call(arguments);
return args.map(function(arg) { return arg });
});
resultPromise.done(function(results) {
ms.setValue(results);
ms.setDataUrlParams({});
$('.input')
});
});
}
There has to be a way to generalize this, but I'm new at promises and $.Deferred so I've been hitting a wall of understanding.
The other fields I'll be instantiating with MagicSuggest will be using different URLs for the $.getJSON() method (probably all using IDs though) (used for finding what the user had previously chosen, thus what to pre-populate the field with), and will obviously have different JSON responses for those calls. So, the trouble spots for me are how to get this all to work together and still DRY.
As soon as I start breaking apart addDefaults() I hit problems because ms is undefined in resultPromise.done, the URLs with the IDs in them, and the json structure inside the $.each command.
How would you refactor this to be more re-usable? Comments/explanations on promises and deferred are always helpful too.

With a fresh head after a few days rest, and with the insight of this post I realized I didn't need to do all this just to add default values. Thankfully, just adding the following to the init worked perfectly: value: msField.attr('data-default').split(','), (I'm adding the values into the HTML under the data-default attribute via PHP.
Code: deleted.
Problem: solved.

Related

Save params from the first call of a recursive function

I have a function that searches files in folders and recursivly calles itself if a subfolder occurs.
I want to optimize the search algo in that way that i can store the returned data and it's corresponding parameters.
So if a new search is issued. I can check if an equal search was made before and return the saved result instead of doing a new search.
My approach was to push the params into the resulting array at first or last. But this has to happen only one time in the whole recursion process.
This is my function:
/**
* List all files that the matcher has hit
* #param {String} start path from where to start the search
* #param {Object} [options] search options
* #param {RegExp} [options.matcher] expression to match while searching
* #param {Boolean} [options.folders] search in subfolders, default = true
* #returns {Array} files that the matcher has hit
*/
list(start, { matcher, folders = true } = {}) {
if (!fs.existsSync(start)) throw new Error(`${start} doesn't exists.`)
const dir = fs.readdirSync(start)
const files = []
for (let iCnt = 0; iCnt < dir.length; iCnt++) {
const item = path.resolve(start, dir[iCnt])
let stat = fs.statSync(item)
switch (true) {
case stat.isDirectory() && folders:
files.push(...list(item, { matcher, folders }))
break
case matcher && matcher.test(item):
files.push(item)
break
case !matcher:
files.push(item)
break
}
}
return files
}
I thought a lot about it. But can't get my head around.
Does anyone have an idea?
When the first call in a recursive sequence is special, I usually handle it by making the recursive part a worker function, and making the main function a wrapper for it that does the special part.
In your case, that would mean renaming your existing list (perhaps to listWorker) and making a wrapper list function that does the caching. Roughly:
function list(start, { matcher, folders = true } = {}) {
let result = getFromCache(/*...*/);
if (!result) {
result = listWorker(start, {matcher, folders});
putInCache(/*...*/, result);
}
return result;
}

How to include js files in header of wordpress pages that are activated on-click

I am attempting to use wordpress to build a website that integrates google maps. I am doing some overlays with the maps and use the google developers API and Python to make the appropriate javascript. I have successfully written the js files and Python necessary to accomplish this.
My website is built in Worpress and I would like add a page (not the home page) that has n links and each one would populate a box with the corresponding map. I can take care of the layout and design issues but I am at a loss on how to:
a) Include the javascript as a file that
b) gets called upon clicking the link and thus populates that map without calling a new page
That is, the javascript is HUGE because it may include thousands of lat/lon points. Therefore including n of these written into the header is unreasonable. I want to simply call it from filename.js when the link is clicked.
There is a plugin that allows me to include whatever I want in the header. So, if I can find out where to put the *.js files (or txt file) in the directory tree and how to have the corresponding file activated upon click I should be good. Thanks!
This Display different maps with onClick event - Google Maps V3. kind of helps with doing an on-click display but everyone's solution was to make one map. I cannot do that. I am overlaying vast amounts of data.
Here is a way you can get that done. (Jump down to the get started part of the script.)
For brevity, I've included a bunch of scripts in one 'file', but you'll want to break them in to individual files.
You may also need to try the html and js in jsbin js bin example, b/c SO may or may not allow the dynamic loading of js.
(function(undefined) {
/**
* #author (#colecmc)
* #method turn collection into an array
* #param {object} collection - NodeList, HTMLCollection, etc. Should have an "item" method and/or a "length" property
*/
ToArray = collection => Array.prototype.slice.call(collection);
/** \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ **/
Observer = (function(undefined) {
/**
* pub sub
*/
'use strict';
var subUid = -1;
return {
topics: {},
subscribe: function(topic, func) {
/**
* #param {string} topic
* #param {function} func
* #returns {string} - a token such as '3'
* #example Observer.subscribe('any-valid-string',function(name,resp){
console.log(resp.prop);
});
*/
if (!Observer.topics[topic]) {
Observer.topics[topic] = [];
}
var token = (++subUid).toString();
Observer.topics[topic].push({
token: token,
func: func
});
return token;
},
publish: function publish(topic, args) {
/**
* #param {string} topic
* #param {object} args
* #returns {boolean} - true if topic is valid, false otherwise
* #example Observer.publish('any-valid-string',{
prop: 'this is a test'
});
*/
if (!Observer.topics[topic]) {
return false;
}
setTimeout(function() {
var subscribers = Observer.topics[topic],
len = subscribers ? subscribers.length : 0;
while (len--) {
subscribers[len].func(topic, args);
}
}, 0);
return true;
},
unsubscribe: function unsubscribe(token) {
/**
* #param {string} token - value should be saved from the original subscription
* #example Observer.unsubscribe('2');
* #example Observer.unsubscribe(member); - where member is the value returned by Observer.subscribe();
*/
var m,
forEachTopic = function(i) {
if (Observer.topics[m][i].token === token) {
Observer.topics[m].splice(i, 1);
return token;
}
};
for (m in Observer.topics) {
if (Observer.topics.hasOwnProperty(m)) {
Observer.topics[m].forEach(forEachTopic);
}
}
return false;
}
};
}(undefined));
/** \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ **/
SetAttributes = function(el, attrs) {
/**
* #author (#colecmc)
* #method simple for in loop to help with creating elements programmatically
* #param {object} el - HTMLElement attributes are getting added to
* #param {object} attrs - object literal with key/values for desired attributes
* #example SetAttributes(info,{
* 'id' : 'utswFormInfo'
* 'class' : 'my-class-name'
* });
*/
'use strict';
var key;
for (key in attrs) {
if (attrs.hasOwnProperty(key)) {
el.setAttribute(key, attrs[key]);
}
}
return el;
};
/** \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ **/
GetScript = function(url, fullPath) {
/**
* #author (#colecmc)
* #version 1.0.4
* #requires Swlxws.SetAttributes, Swlxws.Observer
* #method dynamically add script tags to the page.
* #param {string} url - relative path and file name - do not include extension
* #param {string} fullPath - absolute path
* #example GetScript('myLocalScript');
* #example GetScript('','https://www.google-analytics.com/analytics.js');
*/
'use strict';
function onLoad(event) {
var result;
if (event.type === 'load') {
result = 1;
} else {
result = -1;
}
Observer.publish('get-script-onload-complete', {
successful: result,
eventData: event
});
}
var JSPATH = '/js/',
/* or where ever you keep js files */
el = document.createElement('script'),
attrs = {
defer: true,
src: null,
type: 'text/javascript'
};
/** look for a string based, protocol agnostic, js file url */
if (typeof fullPath === 'string' && fullPath.indexOf('http') === 0) {
attrs.src = fullPath;
}
/** look for any string with at least 1 character and prefix our root js dir, then append extension */
if (typeof url === 'string' && url.length >= 1) {
attrs.src = JSPATH + url + '.js';
}
SetAttributes(el, attrs);
el.addEventListener('load', onLoad);
el.addEventListener('error', onLoad);
document.body.appendChild(el);
return el;
};
/** \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ **/
/**
* Get Started
*/
function onClick(event) {
GetScript('', event.target.dataset.namespaceUrl);
}
Observer.subscribe('get-script-onload-complete', function(name, resp) {
/** check to make resp is what you expect, ie: the correct script loaded */
/** then it is safe to use */
});
ToArray(document.querySelectorAll('.load-scripts')).map(script => script.addEventListener('click', onClick, false));
}(undefined));
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>How to include js files in header of wordpress pages that are activated on-click</title>
</head>
<body>
Load Google Analytics
</body>
</html>
You can use the function wp_enqueue_script() to load the necessary JS files on only the templates you want.
As for your large data set, I recommend that you cache it in an external .json file and use wp_enqueue_script() to load it only when necessary.
Well if the onclick event suggestion is pretty much what you want and you are just concerned about the large amount of data. Then there are a few ways to tackle it. I am not sure if the dataset is a js file or php/json files but i came across a similar issue on one of my projects, dont remember properly but i was doing something with maxmind's ip/location data set.
So i just splitted the large file into 3 smaller ones. Then i looped through each of the file and if the stuff that i was looking for was found in the file then i just breaked out. And definitely as Brian suggested caching and using a CDN would help a lot.

Access parameter of Node.js module function

im totally new to node.js and i couldn't find a similar question for my problem. I'm sure it's easy to solve for one of u guys... at least i guess.
I'm trying to get a special paragraph of a wikipage using the npm mediawiki module for node.js! I get the paragraph using the pre-defined function as following:
bot.page(title).complete(function (title, text, date) {
//extract section '== Check ==' from wikipage&clean string
var result = S(text).between('== Check ==', '==').s;
});
Thats working. What i want is: to use "result" outside of that code block in other functions. I think it has something to do with callbacks but im not sure how to handle it as this is a pre-defined function from the mediawiki module.
The example function of the module to get a wikipage looks as following:
/**
* Request the content of page by title
* #param title the title of the page
* #param isPriority (optional) should the request be added to the top of the request queue (defualt: false)
*/
Bot.prototype.page = function (title, isPriority) {
return _page.call(this, { titles: title }, isPriority);
};
which uses the following function of the module:
function _page(query, isPriority) {
var promise = new Promise();
query.action = "query";
query.prop = "revisions";
query.rvprop = "timestamp|content";
this.get(query, isPriority).complete(function (data) {
var pages = Object.getOwnPropertyNames(data.query.pages);
var _this = this;
pages.forEach(function (id) {
var page = data.query.pages[id];
promise._onComplete.call(_this, page.title, page.revisions[0]["*"], new Date(page.revisions[0].timestamp));
});
}).error(function (err) {
promise._onError.call(this, err);
});
return promise;
}
There's also a complete callback function and i dont know how to use it:
/**
* Sets the complete callback
* #param callback a Function to call on complete
*/
Promise.prototype.complete = function(callback){
this._onComplete = callback;
return this;
};
How can i access the "result" variable by using callbacks outside the function of the module? I don't know how to handle the callback as it is a pre-defined function of a module...
What i want is: to use "result" outside of that code block in other functions.
You can't. You need to use the result inside that code block (that code block is called a callback function btw.). You can still pass them to other functions, you just need to do it inside that callback function:
bot.page(title).complete(function (title, text, date) {
//extract section '== Check ==' from wikipage&clean string
var result = S(text).between('== Check ==', '==').s;
other_function(result); // <------------- this is how you use it
});

sessionstorage works but returns "undefined" in console. why?

I just build a jquery plugin to handle some data storages.
when i try to read from storage, the result is the read item data. fine for now....
when i add
sessionStorage.setItem('test','some data');
or remove
sessionStorage.removeItem('test');
a item, i allways get a undefined in the console.log
but it do what i it should do.
how can i get rid of the undefined, any ideas ???
what i tried was
var result = sessionStorage.setItem('test','some data');
thought this would print it to a var but it won't ^^
my code:
(function ($) {
$.storage = {
add: function(name,value){
if(typeof value === 'object' )
{
/** convert object to json **/
value = JSON.stringify(value);
}
/** add to storage **/
sessionStorage.setItem(name,value);
},
read: function(name){
/** read from storage **/
var item = sessionStorage.getItem(name);
try {
item = $.parseJSON(item);
}catch(e){}
return item;
},
remove: function(name){
/** delete from storage **/
sessionStorage.removeItem(name);
},
clear: function(){
/** clear storage **/
sessionStorage.clear();
}
}
})(jQuery);
SOLUTION
I tried to add storage in console... when i used it in my script it returned nothing! SORRY
setItem and removeItem doesn't return any value. Thus you are getting undefined. Also note removeItem only accept one parameter.
Reference, Here is function sign for above methods
setItem(key:string, data:string):void
This public method stores data via specified key. Please note that if key was already stored, it will overwrite it. Another thing to consider is that if we store a key, and via sessionStorage.key(0) we obtain that key, then we store another key/data and finally we store again the first key, sessionStorage.key(0) will return the second key/data stored, and not the first one.
removeItem(key:string):void
This public method simply removes a key and related data from the storage.
var result = sessionStorage.setItem('test','some data');
does not return anything.
sessionStorage.setItem('test','some data');
assigns value to 'test'therefore the right hand side does not have any value.
What you want is
sessionStorage.setItem('test','some data');
var result = sessionStorage.getItem('test'); //<- here the right hand side is 'some data'

Integrating a link to my database within the Win 8 App Search Contract

In my Win 8 app, based on a blank template, I have successfully added search contract and it seems to work despite the fact that I have not linked it to any data yet, so, for now, when I search any term in my app it simply takes me to the searchResults page with the message "No Results Found" this is what I was expecting initially.
Now what I wish to do is link my database into the searchResults.js file so that I can query my database. Now outside of the search contract I have tested and connected my Db and it works; I did this using WinJS.xhr, to connect to my web-service which in turn queries my database and returns a JSON object.
In my test I only hardcoded the url, however I now need to do two things. Move the test WinJS.xr data for connecting my DB into the search contract code, and second - change the hardcoded url to a dynamic url that accepts the users search term.
From what I understand of Win 8 search so far the actual data querying part of the search contract is as follows:
// This function populates a WinJS.Binding.List with search results for the provided query.
_searchData: function (queryText) {
var originalResults;
// TODO: Perform the appropriate search on your data.
if (window.Data) {
originalResults = Data.items.createFiltered(function (item) {
return (item.termName.indexOf(queryText) >= 0 || item.termID.indexOf(queryText) >= 0 || item.definition.indexOf(queryText) >= 0);
});
} else {`enter code here`
originalResults = new WinJS.Binding.List();
}
return originalResults;
}
});
The code that I need to transfer into this section is as below; now I have to admit I do not currently understand the code block above and have not found a good resource for breaking it down line by line. If someone can help though it will be truly awesome! My code below, I basically want to integrate it and then make searchString be equal to the users search term.
var testTerm = document.getElementById("definition");
var testDef = document.getElementById("description");
var searchString = 2;
var searchFormat = 'JSON';
var searchurl = 'http://www.xxx.com/web-service.php?termID=' + searchString +'&format='+searchFormat;
WinJS.xhr({url: searchurl})
.done(function fulfilled(result)
{
//Show Terms
var searchTerm = JSON.parse(result.responseText);
// var terms is the key of the object (terms) on each iteration of the loop the var terms is assigned the name of the object key
// and the if stament is evaluated
for (terms in searchTerm) {
//terms will find key "terms"
var termName = searchTerm.terms[0].term.termName;
var termdefinition = searchTerm.terms[0].term.definition;
//WinJS.Binding.processAll(termDef, termdefinition);
testTerm.innerText = termName;
testDef.innerText = termdefinition;
}
},
function error(result) {
testDef.innerHTML = "Got Error: " + result.statusText;
},
function progress(result) {
testDef.innerText = "Ready state is " + result.readyState;
});
I will try to provide some explanation for the snippet that you didn't quite understand. I believe the code you had above is coming from the default code added by Visual Studio. Please see explanation as comments in line.
/**
* This function populates a WinJS.Binding.List with search results
* for the provided query by applying the a filter on the data source
* #param {String} queryText - the search query acquired from the Search Charm
* #return {WinJS.Binding.List} the filtered result of your search query.
*/
_searchData: function (queryText) {
var originalResults;
// window.Data is the data source of the List View
// window.Data is an object defined in YourProject/js/data.js
// at line 16 WinJS.Namespace.defineļ¼ˆ"Data" ...
// Data.items is a array that's being grouped by functions in data.js
if (window.Data) {
// apply a filter to filter the data source
// if you have your own search algorithm,
// you should replace below code with your code
originalResults = Data.items.createFiltered(function (item) {
return (item.termName.indexOf(queryText) >= 0 ||
item.termID.indexOf(queryText) >= 0 ||
item.definition.indexOf(queryText) >= 0);
});
} else {
// if there is no data source, then we return an empty WinJS.Binding.List
// such that the view can be populated with 0 result
originalResults = new WinJS.Binding.List();
}
return originalResults;
}
Since you are thinking about doing the search on your own web service, then you can always make your _searchData function async and make your view waiting on the search result being returned from your web service.
_searchData: function(queryText) {
var dfd = new $.Deferred();
// make a xhr call to your service with queryText
WinJS.xhr({
url: your_service_url,
data: queryText.toLowerCase()
}).done(function (response) {
var result = parseResultArrayFromResponse(response);
var resultBindingList = WinJS.Binding.List(result);
dfd.resolve(result)
}).fail(function (response) {
var error = parseErrorFromResponse(response);
var emptyResult = WinJS.Binding.List();
dfd.reject(emptyResult, error);
});
return dfd.promise();
}
...
// whoever calls searchData would need to asynchronously deal with the service response.
_searchData(queryText).done(function (resultBindingList) {
//TODO: Display the result with resultBindingList by binding the data to view
}).fail(function (resultBindingList, error) {
//TODO: proper error handling
});

Categories

Resources