How to use eval on jquery plugin variable? - dry

I'm using pnotify, the JQuery plugin.
I want to shorten this code:
$.pnotify.defaults.styling = "jqueryui";
$.pnotify.defaults.delay = 1500;
$.pnotify.defaults.title = 'Error'
$.pnotify.defaults.mouse_reset = false;
$.pnotify.defaults.history = false;
Into something like this:
var darray = { 'styling':'\'jqueryui\'', 'delay':'1500', 'title':'\'Error\'', 'mouse_reset':'false', 'history':'false' };
$.each(darray, function(option,choice){
eval("var $.pnotify.defaults." + option + "=" + choice + ";");
});
However, despite trying all sorts of things, I have failed. Here's some of the things I've tried:
var darray = { 'styling':'\'jqueryui\'', 'delay':'1500', 'title':'\'Error\'', 'mouse_reset':'false', 'history':'false' };
$.each(darray, function(option,choice){
eval("var $.pnotify.defaults." + option + "=" + choice + ";");
});
JSONstring='var $.pnotify.defaults.' + option + "=" + choice + ";";
$.parseJSON(JSONstring);
string99 = 'var $\.pnotify\.defaults\.' + option
$.parseJSON('{string99=choice}');
option='var $.pnotify.defaults.'+option;
var JSONObject= {'option':choice};
$.parseJSON(JSONObject);
Fiddle: http://jsfiddle.net/morossive/kayKn/

You could try this (untested, but you get the idea):
var darray = {
styling: 'jqueryui',
delay: 1500,
title: 'Error',
mouse_reset: false,
history: false
};
for (var mbr in darray) {
$.pnotify.defaults[mbr] = darray[mbr];
}
Because JavaScript treats objects like hashtables, we can iterate over their "keys" (for (var mbr in darray)) and assign new values to new keys in objects. For example:
var obj = {...};
// The following are equivalent:
obj.x = 5;
obj['x'] = 5;
However, I think there may be an even more elegant solution to your problem (don't use this if you are worried about overwriting preexisting values in $.pnotify.defaults, however):
$.pnotify.defaults = {
styling: 'jqueryui',
delay: 1500,
title: 'Error',
mouse_reset: false,
history: false
};
I know you asked how to use eval to solve this, but I think in general any alternative to using eval is probably better.

Related

Is it possible to select the word that is being read while using the SpeechSynthesisUtterance API?

Is it possible to select the word that is being read while using the SpeechSynthesisUtterance API?
Is there an event I can use to get the current spoken word and cursor position?
Here is what I have so far:
var msg = new SpeechSynthesisUtterance();
var voices = window.speechSynthesis.getVoices();
msg.voice = voices[10]; // Note: some voices don't support altering params
msg.voiceURI = 'native';
msg.volume = 1; // 0 to 1
msg.rate = 1; // 0.1 to 10
msg.pitch = 2; //0 to 2
msg.text = 'Hello World';
msg.lang = 'en-US';
msg.onend = function(e) {
console.log('Finished in ' + event.elapsedTime + ' seconds.');
};
speechSynthesis.speak(msg);
Example from here.
There was a related question that wrote out the words out to a span and I've extended that answer here to select the words as they are spoken.
var utterance = new SpeechSynthesisUtterance();
utterance.lang = 'en-UK';
utterance.rate = 1;
document.getElementById('playButton').onclick = function(){
var text = document.getElementById('textarea').value;
// create the utterance on play in case user called stop
// reference https://stackoverflow.com/a/47276578/441016
utterance = new SpeechSynthesisUtterance();
utterance.onboundary = onboundaryHandler;
utterance.text = text;
speechSynthesis.speak(utterance);
};
document.getElementById('pauseButton').onclick = function(){
if (speechSynthesis) {
speechSynthesis.pause();
}
};
document.getElementById('resumeButton').onclick = function(){
if (speechSynthesis) {
speechSynthesis.resume();
}
};
document.getElementById('stopButton').onclick = function(){
if (speechSynthesis) {
speechSynthesis.cancel();
}
};
function onboundaryHandler(event){
var textarea = document.getElementById('textarea');
var value = textarea.value;
var index = event.charIndex;
var word = getWordAt(value, index);
var anchorPosition = getWordStart(value, index);
var activePosition = anchorPosition + word.length;
textarea.focus();
if (textarea.setSelectionRange) {
textarea.setSelectionRange(anchorPosition, activePosition);
}
else {
var range = textarea.createTextRange();
range.collapse(true);
range.moveEnd('character', activePosition);
range.moveStart('character', anchorPosition);
range.select();
}
};
// Get the word of a string given the string and index
function getWordAt(str, pos) {
// Perform type conversions.
str = String(str);
pos = Number(pos) >>> 0;
// Search for the word's beginning and end.
var left = str.slice(0, pos + 1).search(/\S+$/),
right = str.slice(pos).search(/\s/);
// The last word in the string is a special case.
if (right < 0) {
return str.slice(left);
}
// Return the word, using the located bounds to extract it from the string.
return str.slice(left, right + pos);
}
// Get the position of the beginning of the word
function getWordStart(str, pos) {
str = String(str);
pos = Number(pos) >>> 0;
// Search for the word's beginning
var start = str.slice(0, pos + 1).search(/\S+$/);
return start;
}
<textarea id="textarea" style="width:100%;height:150px;">
Science Literacy is a way of approaching the world. It's a way of equipping yourself to interpret what happens in front of you. It's methods and tools that enable it to act as a kind of a utility belt necessary for what you encounter in the moment. It's methods of mathematical analysis, interpretation, some basic laws of physics so when someone says I have these two crystals and if you rub them together you get healthy. Rather than just discount it, because that's as lazy as accepting it, what you should do is inquire.
So do you know how to inquire? Every scientist would know how to start that conversation. Where did you get these? What does it cure? How does it work? How much does it cost? Can you demonstrate? Science literacy is vaccine against charlatans of the world that would exploit your ignorance of the forces of nature. Become scientifically literate.
</textarea><br>
<input type="button" id="playButton" value="Play"/>
<input type="button" id="pauseButton" value="Pause"/>
<input type="button" id="resumeButton" value="Resume"/>
<input type="button" id="stopButton" value="Stop"/>
MDN SpeechSynthesis
MDN SpeechSynthesisEvent
MDN Boundary
//NOTE: A USER MUST INTERACT WITH THE BROWSER before sound will play.
const msg = new SpeechSynthesisUtterance();
const voices = window.speechSynthesis.getVoices();
msg.voice = voices[10]; // Note: some voices don't support altering params
msg.voiceURI = 'native';
msg.volume = 1; // 0 to 1
msg.rate = 1; // 0.1 to 10
msg.pitch = 2; //0 to 2
txt = "I'm fine, borderline, so bad it hurts Think fast with your money cause it can't get much worse I get told that I'm far too old for number one perks".split(" ")
msg.text = txt;
msg.lang = 'en-US';
msg.onend = function(e) {
console.log('Finished in ' + event.elapsedTime + ' seconds.');
};
let gap = 240
let i = 0
speakTrack = setInterval(() => {
console.log(txt[i++])
//i++ < dont forget if you remove console log
if (i >= txt.length) {
i = 0
clearInterval(speakTrack)
}
}, gap)
speechSynthesis.speak(msg);
https://jsfiddle.net/Vinnywoo/bvt314sa

How to send the index of a for loop into the promise of a function in a Vue Resource call?

I am looping through an object however in the asynchronous part the i variable is always five.
How can I maintain that value, or pass it into the function
getProductData: function() {
var vm = this;
for (var i = 0; i < vm.recommendationResponse['recommendedItems'].length; i++) {
var sku = vm.recommendationResponse['recommendedItems'][i]['items'][0]['id'];
vm.$http.get('http://127.0.0.1:8000/models/api/productimage/' + sku).then(response => {
// get body data
vm.recommendationResponse['recommendedItems'][i]['items'][0]['image_url'] = response.body['product_image_url'];
vm.recommendationResponse['recommendedItems'][i]['items'][0]['price'] = response.body['price'];
}, response => {
vm.recommendationResponse['recommendedItems'][i]['items'][0]['image_url'] = '';
vm.recommendationResponse['recommendedItems'][i]['items'][0]['price'] = '';
});
}
}
I I do something like this:
vm.$http.get('http://127.0.0.1:8000/models/api/productimage/' + sku).then((response, i) => ...
then i is undefined
Who do I keep the index of the loop or should I go about it a different way?
Always use let to initialize variables in for loop when dealing with async operations. Similar things goes to having for loops in intervals. By using let you make sure you always have a unique variable assigned to i.
for (let i = 0, recommendationlength = vm.recommendationResponse['recommendedItems'].length; i < recommendationlength; i++)
Little bonus, if you cache array length in the beginning you get a small performance boost :-)
You could use Array.prototype.forEach instead:
var vm = this;
vm.recommendataionResponse['recommendedItems'].forEach((item, i) => {
var sku = vm.recommendationResponse['recommendedItems'][i]['items'][0]['id'];
vm.$http.get('http://127.0.0.1:8000/models/api/productimage/' + sku).then(response => {
// get body data
vm.recommendationResponse['recommendedItems'][i]['items'][0]['image_url'] = response.body['product_image_url'];
vm.recommendationResponse['recommendedItems'][i]['items'][0]['price'] = response.body['price'];
}, response => {
vm.recommendationResponse['recommendedItems'][i]['items'][0]['image_url'] = '';
vm.recommendationResponse['recommendedItems'][i]['items'][0]['price'] = '';
});
})
This way, since there is a unique scope for each i value, each .then callback will be able to reference the correct value.

Sensenet Content Picker Customization

I created two custom content types, ProjectContract and PaymentRequest. Under PaymentRequest, I have a reference field Contract which I would like to use to reference ProjectContract. When I am creating/changing PaymentRequest, I need the following:
how can I initialize Content Picker to display ContractNumber field of available ProjectContracts?
how can I display selected ProjectContract's ContractNumber under ReferenceField Grid control?
The SN js code and the mvc contains/returns fix field values. I did not find any setting where I can add custom fields to show.
First of all, what is the version of that SN package, because the oData.svc request will not work on older versions. It is available from 6.2.
About the oData, here is a link: http://wiki.sensenet.com/OData_REST_API
There is another way to solve it, but with this, you need to modify the existion SN codes.
You need to copy (" /Root/Global/scripts/sn/SN.Picker.js ") file into your skin folder with the same structure. (" /Root/Skins/[yourskinfolder]/scripts/sn/SN.ReferenceGrid.js ")
You need to copy (" /Root/Global/scripts/sn/SN.ReferenceGrid.js ") file into your skin folder as well.
Do not modify the original SN file, because it will be overwrite after an SN update.
Next step: copy the following code to line 1068, before the ("$grid.jqGrid({") line, into the InitGrid function.
...
var neededTypeName = "ProjectContract";
var neededFieldName = "ContractNumber";
var findField = false;
o2 = (function () {
var result = [];
var itemArray = [];
$.each(o2, function (index, el) {
el.ContentField = "";
result.push(el);
if (el.ContentTypeName == neededTypeName) {
itemArray.push([index, el.Path]);
findField = true;
}
});
if (findField) {
$.each(itemArray, function (itemIndex, itemElArray) {
var itemId = itemElArray[0];
var itemEl = itemElArray[1];
var thisLength = itemEl.length;
var thislastSplash = itemEl.lastIndexOf("/");
var thisPath = itemEl.substring(0, thislastSplash) + "('" + itemEl.substring(thislastSplash + 1, thisLength) + "')";
$.ajax({
url: "/oData.svc" + thisPath + "?metadata=no$select=Path," + neededFieldName,
dataType: "json",
async: false,
success: function (d) {
result[itemId].ContentField = d.d[neededFieldName];
}
});
});
colNames.splice(6, 0, "ContentField");
colModel.splice(6, 0, { index: "ContentField", name: "ContentField", width: 100 });
return result;
}
return o2;
})();
...
$grid.jqGrid({
...
The "neededTypeName" may contains your content type value, and the "neededFieldName" may contains the field name you want to render.
The other will build up the grid.
This will modify the Content picker table.
You need to add this code into the GetResultDataFromRow function, at line 660 before the return of the function.
...
if (rowdata.ContentField != undefined) {
result.ContentField = rowdata.ContentField;
}
...
This will add the selected item properties from the Content picker to the reference field table.
Then you need to open the SN.ReferenceGrid.js and add the following code into the init function before the "var $grid = $("#" + displayAreaId);"
var neededTypeName = "CustomItem2";
var neededFieldName = "Custom2Num";
var findField = false;
var alreadyAdded = false;
var btnAttr = $("#"+addButtonId).attr("onClick");
if (btnAttr.indexOf(neededTypeName) > -1) {
alreadyAdded = true;
colNames[4].width = 150;
colModel[4].width = 150;
colNames.splice(3, 0, "ContentField");
colModel.splice(3, 0, { index: "ContentField", name: "ContentField", width: 60 });
}
initialSelection = (function () {
var result = [];
var itemArray = [];
$.each(initialSelection, function (index, el) {
el.ContentField = "";
result.push(el);
if (el.ContentTypeName == neededTypeName) {
itemArray.push([index, el.Path]);
findField = true;
}
});
if (findField) {
$.each(itemArray, function (itemIndex, itemElArray) {
var itemId = itemElArray[0];
var itemEl = itemElArray[1];
var thisLength = itemEl.length;
var thislastSplash = itemEl.lastIndexOf("/");
var thisPath = itemEl.substring(0, thislastSplash) + "('" + itemEl.substring(thislastSplash + 1, thisLength) + "')";
$.ajax({
url: "/oData.svc" + thisPath + "?metadata=no$select=Path," + neededFieldName,
dataType: "json",
async: false,
success: function (d) {
result[itemId].ContentField = d.d[neededFieldName];
}
});
});
if (!alreadyAdded) {
colNames.splice(3, 0, "ContentField");
colModel.splice(3, 0, { index: "ContentField", name: "ContentField", width: 100 });
}
return result;
}
return initialSelection;
})();
I hope this will help but the SN version should be helpful.

Mootools variable scope issues

I have a problem getting my mind round variable scope and could do with some help :)
I'm setting up a module in joomla that will rotate images. I've a bit of code I've used on non Joomla sites that works fine. However I've ported it and I'm running into problems that I think are variable scope issues so any thoughts would be great.
Sorry for the long code but I included the whole function in case (when it works) it might help someone else.
function slideshow(container,containerCaption,previewCode,timer,classis,headerId,thumbOpacity,titlebar){
var showDuration = timer;
var container = $(container);
var images = $(container).getElements('span');
var currentIndex = 0;
var interval;
var preview = new Element('div',{
id: containerCaption,
styles: {
opacity: thumbOpacity
}
}).inject(container);
preview.set('html',previewCode);
images.each(function(img,i){
if(i > 0) {
img.set('opacity',0);
}
});
var show = function() {
images[currentIndex].fade('out');
images[currentIndex = currentIndex < images.length - 1 ? currentIndex+1 : 0].fade('in');
var title = '';
var captionText = '';
if(images[currentIndex].get('alt')) {
cap = images[currentIndex].get('alt').split('::');
title = cap[0];
captionText = cap[1];
urltoUse = cap[2];
preview.set('html','<span class="lctf1"><ahref="'+urltoUse+'">'
+ title + '</a></span>'
+ (captionText ? '<p>' + captionText + '</p>' : ''));
}
};
window.addEvent('domready',function(){
interval = show.periodical(showDuration);
});
}
window.addEvent('domready',function() {
container = "slideshow-container";
containerCaption ="slideshow-container-caption";
previewCode = '<span ><?php echo $itemtitle[0];?></span><p ><?php echo $itemdesc[0];?></p>';
timer = <?php echo $slidetime*1000;?>;
classis = 1;
headerId = "";
thumbOpacity =0.7;
titlebar = "<?php echo $showTitle;?>";
if($(container)){
slideshow(container,containerCaption,previewCode,timer,classis,headerId,thumbOpacity,titlebar);
}
});
The javascript error being thrown is that preview is undefined.
Your code seems to work, I made a jsfiddle here: http://jsfiddle.net/7E2MX/3/ which runs with no errors.
I did change one line though:
var images = $(container).getElements('span');
to
var images = $(container).getElements('img');

Adding Columns Dynamically to SlickGrid with AJAX. Columns don't show up

Using SlickGrid to display some pretty elaborate grids. The Example I am showing here isn't my code but basically an example given by the SlickGrid people duplicating my issue. My Grids need to have columns added dynamically with the column names being fed through an AJAX feed. Creating the column object in JS is not a problem and even adding them using the .push is seems to work fine as I can see them in the firebug console. The new columns never seem to rendner. I get a a bunch of tiny empty cells at the end of the grid but they never populate.
The script below can be replaced with the script in the "example1-simple.html" viewed here.
<script src="../lib/jquery.jsonp-1.1.0.min.js"></script>
<script>
var grid;
var data = [];
var columns = [
{id:"title", name:"Title", field:"title"},
{id:"duration", name:"Duration", field:"duration"},
{id:"%", name:"% Complete", field:"percentComplete"},
{id:"start", name:"Start", field:"start"},
{id:"finish", name:"Finish", field:"finish"},
{id:"effort-driven", name:"Effort Driven", field:"effortDriven"}
];
var dynamicColumns = [];
var options = {
enableCellNavigation: true,
enableColumnReorder: false
};
$(function() {
data = [];
BuildExtraColumnsAJAX();
for (var i = 0; i < 2000; i++) {
data[i] = {
title: "Task " + i,
duration: "5 days",
percentComplete: Math.round(Math.random() * 100),
start: "01/01/2009",
finish: "01/05/2009",
effortDriven: (i % 5 == 0)
};
for (var x = 0; x < 20; x++) {
var columnName = "dynamicColumn" + x;
data[i][columnName] = x;
}
}
//alert("Go Pack Go");
grid = new Slick.Grid("#myGrid", data, dynamicColumns, options);
$("#myGrid").show();
})
function BuildExtraColumnsAJAX(){
//dynamicColumns = [];
for (var x = 0; x < columns.length; x++){
dynamicColumns.push(columns[x]);
}
var url = "http://services.digg.com/search/stories? query=apple&callback=C&offset=0&count=20&appkey=http://slickgrid.googlecode.com&type=javascript";
$.jsonp({
url: url,
callbackParameter: "callback",
cache: true, // Digg doesn't accept the autogenerated cachebuster param
success: onSuccess,
error: function(){
alert("BOOM Goes my world");
}
});
}
function onSuccess(resp) {
for (var i = 0; i < resp.stories.length; i++) {
dynamicColumns.push( {
id: "dynamicColumn" + i,
name: "Dynamic Column" + i,
field: "dynamicColumn" + i
});
}
}
function BuildExtraColumns(){
dynamicColumns = [];
for (var x = 0; x < columns.length; x++){
dynamicColumns.push(columns[x]);
}
for (var i = 0; i < 20; i++) {
dynamicColumns.push( {
id: "dynamicColumn" + i,
name: "Dynamic Column" + i,
field: "dynamicColumn" + i
});
}
}
If I put the line grid = new Slick.Grid("#myGrid", data, dynamicColumns, options); in the firebug console and run it the grid than renders fine. It is almost like the script is still executing lines of code even though its not done creating the dynamicColumns.
The Digg AJAX call is just to similute an AJAX call, I of course would be using my own.
The grid is getting initialized before the AJAX call to get the additional columns completes.
Either wait until the columns have loaded to initialize the grid, or update the grid after the additional columns have loaded:
grid.setColumns(dynamicColumns);