I am using Typeahead by twitter. I am running into this warning from Intellij. This is causing the "window.location.href" for each link to be the last item in my list of items.
How can I fix my code?
Below is my code:
AutoSuggest.prototype.config = function () {
var me = this;
var comp, options;
var gotoUrl = "/{0}/{1}";
var imgurl = '<img src="/icon/{0}.gif"/>';
var target;
for (var i = 0; i < me.targets.length; i++) {
target = me.targets[i];
if ($("#" + target.inputId).length != 0) {
options = {
source: function (query, process) { // where to get the data
process(me.results);
},
// set max results to display
items: 10,
matcher: function (item) { // how to make sure the result select is correct/matching
// we check the query against the ticker then the company name
comp = me.map[item];
var symbol = comp.s.toLowerCase();
return (this.query.trim().toLowerCase() == symbol.substring(0, 1) ||
comp.c.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1);
},
highlighter: function (item) { // how to show the data
comp = me.map[item];
if (typeof comp === 'undefined') {
return "<span>No Match Found.</span>";
}
if (comp.t == 0) {
imgurl = comp.v;
} else if (comp.t == -1) {
imgurl = me.format(imgurl, "empty");
} else {
imgurl = me.format(imgurl, comp.t);
}
return "\n<span id='compVenue'>" + imgurl + "</span>" +
"\n<span id='compSymbol'><b>" + comp.s + "</b></span>" +
"\n<span id='compName'>" + comp.c + "</span>";
},
sorter: function (items) { // sort our results
if (items.length == 0) {
items.push(Object());
}
return items;
},
// the problem starts here when i start using target inside the functions
updater: function (item) { // what to do when item is selected
comp = me.map[item];
if (typeof comp === 'undefined') {
return this.query;
}
window.location.href = me.format(gotoUrl, comp.s, target.destination);
return item;
}
};
$("#" + target.inputId).typeahead(options);
// lastly, set up the functions for the buttons
$("#" + target.buttonId).click(function () {
window.location.href = me.format(gotoUrl, $("#" + target.inputId).val(), target.destination);
});
}
}
};
With #cdhowie's help, some more code:
i will update the updater and also the href for the click()
updater: (function (inner_target) { // what to do when item is selected
return function (item) {
comp = me.map[item];
if (typeof comp === 'undefined') {
return this.query;
}
window.location.href = me.format(gotoUrl, comp.s, inner_target.destination);
return item;
}}(target))};
I liked the paragraph Closures Inside Loops from Javascript Garden
It explains three ways of doing it.
The wrong way of using a closure inside a loop
for(var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
Solution 1 with anonymous wrapper
for(var i = 0; i < 10; i++) {
(function(e) {
setTimeout(function() {
console.log(e);
}, 1000);
})(i);
}
Solution 2 - returning a function from a closure
for(var i = 0; i < 10; i++) {
setTimeout((function(e) {
return function() {
console.log(e);
}
})(i), 1000)
}
Solution 3, my favorite, where I think I finally understood bind - yaay! bind FTW!
for(var i = 0; i < 10; i++) {
setTimeout(console.log.bind(console, i), 1000);
}
I highly recommend Javascript garden - it showed me this and many more Javascript quirks (and made me like JS even more).
p.s. if your brain didn't melt you haven't had enough Javascript that day.
You need to nest two functions here, creating a new closure that captures the value of the variable (instead of the variable itself) at the moment the closure is created. You can do this using arguments to an immediately-invoked outer function. Replace this expression:
function (item) { // what to do when item is selected
comp = me.map[item];
if (typeof comp === 'undefined') {
return this.query;
}
window.location.href = me.format(gotoUrl, comp.s, target.destination);
return item;
}
With this:
(function (inner_target) {
return function (item) { // what to do when item is selected
comp = me.map[item];
if (typeof comp === 'undefined') {
return this.query;
}
window.location.href = me.format(gotoUrl, comp.s, inner_target.destination);
return item;
}
}(target))
Note that we pass target into the outer function, which becomes the argument inner_target, effectively capturing the value of target at the moment the outer function is called. The outer function returns an inner function, which uses inner_target instead of target, and inner_target will not change.
(Note that you can rename inner_target to target and you will be okay -- the closest target will be used, which would be the function parameter. However, having two variables with the same name in such a tight scope could be very confusing and so I have named them differently in my example so that you can see what's going on.)
In ecmascript 6 we have new opportunities.
The let statement declares a block scope local variable, optionally initializing it to a value.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
Since the only scoping that JavaScript has is function scope, you can simply move the closure to an external function, outside of the scope you're in.
Just to clarify on #BogdanRuzhitskiy answer (as I couldn't figure out how to add the code in a comment), the idea with using let is to create a local variable inside the for block:
for(var i = 0; i < 10; i++) {
let captureI = i;
setTimeout(function() {
console.log(captureI);
}, 1000);
}
This will work in pretty much any modern browser except IE11.
Related
I’m getting a JSHint/JSLint error on my code below.
Functions declared within loops referencing an outer scoped variable may lead to confusing semantics. ($, currentVal)
This is directed at the $options.each loop where I’m pushing to currentVal.
Any thoughts on how to solve this?
$(".option input[type=radio]").change(function() {
reload_filterstring(this);
});
$(".option input[type=checkbox]").change(function() {
reload_filterstring(this);
});
function reload_filterstring(that) {
var finalFilterQuery = {};
var currentEl = "";
(filterType = $this.attr("data-filter-type")),
($options = $this.find("ul.options input")),
(query = $this.find('input[name="query"]')),
(finalQuery = $('input[name="finalQuery"]')),
(filterData = []),
(filterQuery = null);
// console.log(filterName);
currentVal = [];
$options.each(function() {
if ($(this).prop("checked") == true) {
currentVal.push($(this).attr("id"));
}
});
finalFilterQuery[filterName] = currentVal.join("|");
}
// console.log(finalFilterQuery);
var str = "";
for (var key in finalFilterQuery) {
if (finalFilterQuery.hasOwnProperty(key)) {
if (str != "") {
str += ",";
}
str += key + "=" + finalFilterQuery[key];
}
}
console.log(str);
}
https://codepen.io/anon/pen/drMRem?editors=1111
I ran with codepen.io JS Analyse and the result was: Don't make functions within a loop. with a link to this JS Hint - don't make functions within a loop. You should move the function out instead of placing it inside a loop, but if you still insist on having a function inside the loop, you can narrow down the scope of currentVal inside the function like below:
$options.each(function($currentVal) {
return function() {
if ($(this).prop("checked") == true) {
$currentVal.push($(this).attr("id"));
};
}(currentVal));
I have a SCOPE problem. When I declare "var text" outside the function all works. But inside the function it works only in the first part. Here is what I mean:
This is a buffer function. Executing buffer("anything") saves "anything". Executing buffer() - without the properties will return all properties.
buffer("Al")
buffer("ex")
buffer() <= should return Alex
But the SCOPE of "text" is wrong and it does not return the saved properties.
function makeBuffer() {
var text = "";
if (arguments.length != 0) {
for (let i = 0; i < arguments.length; i++) {
console.log(`Adding argument - (${arguments[i]})`);
text += arguments[i];
console.log(`New text - (${text})`);
}
} else {
console.log(`text - (${text})`);
return text;
}
}
var buffer = makeBuffer;
buffer("One", "Two");
document.write(buffer());
That is normal behaviour.
A variable defined in a given scope goes away when the scope goes away. Each call the to the function creates a new scope.
Declaring the variable outside the function is the standard way to share a value between invocations of it.
What you want is a factory:
function makeBuffer() {
var text = "";
return function buffer() {
if (arguments.length != 0) {
for (let i = 0; i < arguments.length; i++) {
console.log(`Adding argument - (${arguments[i]})`);
text += arguments[i];
console.log(`New text - (${text})`);
}
} else {
console.log(`text - (${text})`);
return text;
}
}
}
var buffer = makeBuffer();
buffer("One", "Two");
document.write(buffer());
You could do this using an object. This will make your code much more organized.
var Buffer = function() {
this.text = "";
}
Buffer.prototype.append = function() {
for (var i = 0; i < arguments.length; i++) {
this.text += arguments[i];
}
}
Buffer.prototype.get = function() {
return this.text;
}
var buffer = new Buffer();
buffer.append("One", "Two");
document.write(buffer.get());
Using ES6 the syntax gets even sweeter:
class Buffer {
constructor() {
this.text = "";
}
append() {
this.text = this.text.concat(...arguments);
}
get() {
return this.text;
}
}
var buffer = new Buffer();
buffer.append("One", "Two");
document.write(buffer.get());
As Quentin properly pointed out in his answer, that is a normal behavior.
An alternative option to keep the value on your function without declaring the variable outside is scope is to add it as a property to the function itself.
As in JavaScript a function is a first class object, you can put such data directly into function object (like in any other objects).
An example below, please note how to get property text from your function (buffer.text).
function makeBuffer() {
makeBuffer.text = "";
if (arguments.length != 0) {
for (let i = 0; i < arguments.length; i++) {
console.log(`Adding argument - (${arguments[i]})`);
makeBuffer.text += arguments[i];
console.log(`New text - (${makeBuffer.text})`);
}
} else {
console.log(`text - (${makeBuffer.text})`);
return makeBuffer.text;
}
}
var buffer = makeBuffer;
buffer("Al", "ex");
console.log(`buffer.text - (${buffer.text})`);
Alternatively consider using a closure in order to keep the value of text between function calls.
Closures are functions that refer to independent (free) variables
(variables that are used locally, but defined in an enclosing scope).
In other words, these functions 'remember' the environment in which
they were created. More info here.
let makeBuffer = function() {
// closure
let text = "";
return function() {
if (arguments.length != 0) {
for (let i = 0; i < arguments.length; i++) {
console.log(`Adding argument - (${arguments[i]})`);
text += arguments[i];
console.log(`New text - (${text})`);
}
} else {
console.log(`text - (${text})`);
return text;
}
}
};
var buffer = makeBuffer();
buffer("Al", "ex");
I have a JavaScript function that I want to fire once the user enters text inside an input element. Currently I can only see the function firing if I console.log it. How do I get it to fire using keyup method?
The relevant code is below.
var $ = function (selector) {
var elements = [],
i,
len,
cur_col,
element,
par,
fns;
if(selector.indexOf('#') > 0) {
selector = selector.split('#');
selector = '#' + selector[selector.length -1];
}
selector = selector.split(' ');
fns = {
id: function (sel) {
return document.getElementById(sel);
},
get : function(c_or_e, sel, par) {
var i = 0, len, arr = [], get_what = (c_or_e === 'class') ? "getElementsByClassName" : "getElementsByTagName";
if (par.length) {
while(par[I]) {
var temp = par[i++][get_what](sel);
Array.prototype.push.apply(arr, Array.prototype.slice.call(temp));
}
} else {
arr = par[get_what](sel);
}
return (arr.length === 1)? arr[0] : arr;
}
};
len = selector.length;
curr_col = document;
for ( i = 0; i < len; i++) {
element = selector[i];
par = curr_col;
if( element.indexOf('#') === 0) {
curr_col = fns.id(element.split('#'[1]));
} else if (element.indexOf('.') > -1) {
element = element.split('.');
if (element[0]) {
par = fns.get('elements', element[0], par);
for ( i =0; par[i]; i++) {
if(par[i].className.indexOf(element[1]> -1)) {
elements.push(par[i]);
}
}
curr_col = elements;
} else {
curr_col = fns.get('class', element[1], par);
}
} else {
curr_col = fns.get('elements', element, par);
}
}
return elements;
};
You need to bind your method to the keyup event on the page.
You could try
document.addEventListener('keyup', $)
Or assuming you have the input element as element you could do
element.addEventListener('keyup', $)
Your function will be passed the event which you could use to investigate the state of the element if you needed that information to trigger or not trigger things in the function.
Here's a quick sample where the function that get's run on keypress is changeColor.
var COLORS = ['red', 'blue','yellow', 'black']
var NCOLORS = COLORS.length;
function changeColor(ev) {
var div = document.getElementById('colored');
var colorIdx = parseInt(Math.random() * NCOLORS);
console.log(colorIdx);
var newColor = COLORS[colorIdx];
div.style.color = newColor
console.log("New color ", newColor)
}
document.body.addEventListener('keyup', changeColor)
Though I'm not using the event (ev), I like to show, in the code, that I expect that variable to be available.
See it in action here - http://codepen.io/bunnymatic/pen/yyLGXg
As a sidenote, you might be careful about calling your function $. Several frameworks (like jQuery) use that symbol and you may run into conflicts where you're overriding the global variable $ or where the framework overrides your version if it.
I'm writing a piece of code to easily save error logs in an object for debugging.
What I'm trying to achieve is to get the Object name from the function it was called from like so:
var MainObject = {
test : function() {
return MainObject.test.caller;
// When called from MainObject.testcaller,
// it should return MainObject.testcaller.
},
testcaller : function() {
return MainObject.test(); // Should return MainObject.testcaller, Returns own function code.
},
anothercaller : function() {
return MainObject.test(); // Should return MainObject.anothercaller, Returns own function code.
}
}
However when I run this code it returns the function code from MainObject.testcaller.
JSFiddle example
Is there any way this is possible?
Update
After looking at Rhumborl's answer, I discovered that assigning the value through another function would lead it to point back at the function name without the object itself.
Code:
(function (name, func) {
MainObject[name] = func;
})('invalid', function() {
return MainObject.test("blah");
});
// This now points at invalid() rather than MainObject.invalid()
Updated fiddle
There is a non–standard caller property of functions that returns the caller function, however that is a pointer to a function object and doesn't tell you the object it was called as a method of, or the object's name. You can get a reference to the function through arguments.callee.
There is also the obsolete arguments.caller, but don't use that. It also provides a reference to the calling function (where supported).
Once you have a reference to the calling function (if there is one), you then have the issue of resolving its name. Given that Functions are Objects, and objects can be referenced by multiple properties and variables, the concept of a function having a particular name is alluvial.
However, if you know that the function is a property of some object, you can iterate over the object's own enumerable properties to find out which one it is.
But that seems to be a rather odd thing to do. What are you actually trying to do? You may be trying to solve a problem that can be worked around in a much more robust and simpler way.
Edit
You can do what you want in a very limited way using the method described above for the case in the OP, however it is not robust or a general solution:
var mainObject = {
test : function() {
var obj = this;
var caller = arguments.callee.caller;
var global = (function(){return this}());
var fnName, objName;
for (var p in global) {
if (global[p] === obj) {
objName = p;
}
}
for (var f in obj) {
if (obj[f] === caller) {
fnName = f;
}
}
return objName + '.' + fnName;
},
testcaller : function() {
return mainObject.test();
},
anothercaller : function() {
return mainObject.test();
}
}
console.log(mainObject.testcaller()); // mainObject.testcaller
console.log(mainObject.anothercaller()); // mainObject.anothercaller
but it's brittle:
var a = mainObject.anothercaller;
console.log(a()); // mainObject.anothercaller
var b = {
foo : mainObject.anothercaller
}
console.log(b.foo()); // mainObject.anothercaller
Oops.
You can use this trick at http://www.eriwen.com/javascript/js-stack-trace/ which throws an error, then parses the stack trace.
I have updated it for the latest versions of Firefox, Chrome and IE. Unfortunately it doesn't work well on my IE9 (and I haven't tested it on Opera).
function getStackTrace() {
var callstack = [];
var isCallstackPopulated = false;
try {
i.dont.exist += 0; //doesn't exist- that's the point
} catch (e) {
if (e.stack) { //Firefox/Chrome/IE11
var lines = e.stack.split('\n');
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i].trim();
if (line.match(/^at [A-Za-z0-9\.\-_\$]+\s*\(/)) {
// Chrome/IE: " at Object.MainObject.testcaller (url:line:char)"
var entry = line.substring(3, line.indexOf('(') - 1);
// Chrome appends "Object." to the front of the object functions, so strip it off
if (entry.indexOf("Object.") == 0) {
entry = entry.substr(7, entry.length);
}
callstack.push(entry);
} else if (line.match(/^[A-Za-z0-9\.\-_\$]+\s*#/)) {
// Firefox: "MainObject.testcaller#url:line:char"
callstack.push(line.substring(0, lines[i].indexOf('#')));
}
}
//Remove call to getStackTrace()
callstack.shift();
isCallstackPopulated = true;
} else if (window.opera && e.message) { //Opera
var lines = e.message.split('\n');
for (var i = 0, len = lines.length; i < len; i++) {
if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
var entry = lines[i];
//Append next line also since it has the file info
if (lines[i + 1]) {
entry += lines[i + 1];
i++;
}
callstack.push(entry);
}
}
//Remove call to getStackTrace()
callstack.shift();
isCallstackPopulated = true;
}
}
if (!isCallstackPopulated) { //IE9 and Safari
var currentFunction = arguments.callee.caller;
while (currentFunction) {
var fn = currentFunction.toString();
var fname = fn.substring(fn.indexOf("function") + 8, fn.indexOf('')) || 'anonymous';
callstack.push(fname);
currentFunction = currentFunction.caller;
}
}
return callstack;
}
var MainObject = {
test: function (x) {
// first entry is the current function (test), second entry is the caller
var stackTrace = getStackTrace();
var caller = stackTrace[1];
return caller + "()";
},
testcaller: function () {
return MainObject.test(1, null);
}
}
function SomeFunction() {
return MainObject.test("blah");
}
document.body.innerHTML += '<b style="color: red">' + MainObject.testcaller() + '</b>';
document.body.innerHTML += '<div>Calling SomeFunction() returns: <b style="color: red">' + SomeFunction() + '</b></div>';
MainObject.test() should return: <b style="color: blue">MainObject.testcaller()</b>
<hr />
MainObject.test() returns:
Updated fiddle here
The handler inside of my for loop might be out of scope and only prints "Last Event added" in console but doesn't loop through each element in the array. No sure where I'm going wrong here, but I need help attaching the event listener to each.
(function () {
if (document.addEventListener) {
this.addEvent = function (elem, type, fn) {
elem.addEventListener(type, fn, false);
};
} else if (document.attachEvent) {
this.addEvent = function (elem, type, fn) {
var bound = function () {
return fn.apply(elem, arguments);
};
elem.attachEvent("on" + type, bound);
return bound;
};
}
if (document.getElementsByClassName) {
this.getClass = function (className) {
return document.getElementsByClassName(className);
};
} else if (document.querySelectorAll) {
this.getClass = function (className) {
return document.querySelectorAll("." + className);
};
}
var elem = getClass("images"),
display = getClass("display_box"),
rolloverImage = function (e) {
console.log("Event 'rolloverImage' triggered");
};
console.log(display);
console.log(elem);
console.log(elem.length);
for (var i = 0; i < elem.length; i++) {
document.addEvent(elem[i], "mouseover", rolloverImage);
if (i = elem.length) {
console.log("Last event added");
} else {
console.log("Event added to " + elem[i]);
}
};
})();
A fiddle is available here: http://jsfiddle.net/bNL5C/
if you are wanting your addEvent function to be on the document object use document.addEvent = not this.addEvent = as that is putting it on the global object window
Also it doesnt loop through all of them because you are assigning i to the elem array length instead of comparing.
if (i = elem.length) {
should be
if (i == elem.length) {
Because of this on the first iteration through the loop causes i to be the value of elem.length and since i is now not < elem.length your loop exits.
One problem is that in your for loop, the if (i = elem.length) will always be true, as you are using a single assignment =, and changing the value of i. This needs to be changed to if (i == elem.length) or perhaps you'd prefer to use ===.