This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
I have an object containing a number of buttons (label and callback) which I dynamically want to add to the DOM:
var buttons = {
'Save': function() {
return false;
},
'Abort': function() {}
};
for(label in buttons) {
$('#buttonbar').append('<button>' + label + '</button>');
var callback = buttons[label];
$('#buttonbar button:last-child').click(function() {
//var result = callback();
alert(callback);
});
}
But regardless which button I click, the variable callback always contains the function of the last button. See this fiddle.
Any ideas how to solve that?
Thanks to the hint given by Barmar I found the solution:
var buttons = {
'Save': function() {
return false;
},
'Abort': function() {}
};
for(label in buttons) {
$('#buttonbar').append('<button>' + label + '</button>');
var callback = buttons[label];
(function(cb) {
$('#buttonbar button:last-child').click(function() {
alert(cb);
});
})(callback);
}
Related
This question already has answers here:
Function in JavaScript that can be called only once
(32 answers)
Closed 6 years ago.
Execute function only one time in Javascript, no matter how many times it has been called.
I write the following code, but does not working.
var counter = 0;
if(n.data === YT.PlayerState.BUFFERING) {
setTimeout(function() {
if(counter===0) {
r.frontPlayer.seekTo(10);
counter++;
}}, 2000);
}
Try not to use timeouts, they invite misery and suffering. This is a simple example, I use jquery for attaching the events but the function is independent of jquery. The key thing is using the object, the anonymous function in this case, to track state.
<button id="testButton">
test
</button>
$("#testButton").click(function() {
if (null == this.ran) {
console.log("do something");
this.ran = true;
}
})
Take a look at underscore or lodash's _.once function:
var fn = _.once(function() {
console.log('this will only run once');
});
Or writing it yourself:
var fn = (function() {
var called = false;
var ret;
return function() {
if (called) return ret;
called = true;
// do stuff
// ..
ret = 'some return value';
return ret;
};
})();
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
i'm trying build slideshow function with OOP literal way.
so, this is my code :
"use strict";
var slideshow = {
elSet : $(".slideshow"),
elCount : indexCount(".dealList"),
elWidth : width(".dealList"),
elNo : 1,
next : function() {
if (this.elNo < this.elCount) {
console.log(this.elSet);
this.elNo += 1;
this.elSet.style.transform = "translateX(-" + this.elWidth * this.elNo + "px)";
}
else {
console.log(this.elSet);
this.elNo = 1;
this.elSet.style.transform = "translateX(-" + this.elWidth * this.elNo + "px)";
}
},
initial : function() {
var loop = setInterval(this.next, 5000);
}
}
slideshow.initial();
the problem occure in browser console :
out of memory
console.log return undefined
it is possible the problem occure because of this keyword?
what's wrong with my code?
The callback of the setInterval() when executed is bound to the global object and not your object. You can, however, bind it to your object by using this code instead:
initial : function() {
var loop = setInterval(this.next.bind( this ), 5000);
}
MDN on bind()
This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
`new function()` with lower case "f" in JavaScript
(3 answers)
Closed 8 years ago.
var ajaxCall = new function () {
var baseUrl = 'Home/',
getCategory = function (callBack) {
$.getJSON(baseUrl + "GetCategories", function (data) {
callBack(data);
});
}
getSubCategory = function (callBack) {
$.getJSON(baseUrl + "GetSubCategories", function (data) {
});
}
return {
getCategory: getCategory,
getSubCategory: getSubCategory
};
}();
This is a part of our front end code. I know that we are creating an object with functions and this renders flexibility.
I wonder two things:
1. the new keyword - why not just leave it like var ajaxCall = function(){}; ??
2. The () at the end of this code snippet, we do we need that?
ANY comments to newbie here is welcome. Thanks.
This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5 answers)
Closed 8 years ago.
I have function with loop and jQuery click function which I would like, after click, execute specific function. The a.id class is important, so like jQuery click definition. After click on element with specific id, I would like execute specific function. What can change is only function b?
var a = {
id: { "id1": function () { console.log(1) }, "id2": function () { console.log(2) }, "id3": function () { console.log(3) } },
b: function () {
$this = this;
for (v in $this.id) {
$("#" + v).click(function () {
$this.id[v]();
});
}
}
}
After i click on element, i want see id1 = 1, id2 = 2, id3 = 3. But this code write value 3 for each element. This example is very simple. Problem is variable reference i know, but i can't find correct solution. Thanks
Wrap it in an IFFE function. Read more about scope and IIFE's here http://benalman.com/news/2010/11/immediately-invoked-function-expression/.
I have provided a fiddle with an example related to your question:
http://jsfiddle.net/rtmeo4nx/3/
function() {
var $this = this;
for (var v = 0; v <= 4; v++) {
(function() {
var i = v;
$("#v" + i).on("click", function(e) {
e.stopPropagation();
alert('hi' + i);
});
})();
}
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a global object declared at first line. Then filling the data into it using jquery getJSON. The issue here is I am getting empty object inside function slider, whereas inside getJSON it is printing proper data. Any idea whats wrong here?
var allslides = {};
$.getJSON("data/slides.json", function(data) {
$.each(data, function(key, val) {
allslides[key] = { image : val.image, title: val.title, desc:val.desc };
});
console.log(allslides); // First
});
$(function(){
slider();
});
function slider() {
console.log(allslides); // second
}
Move your call to slider into your .getJSON as it is asynchronous:
$.getJSON("data/slides.json", function(data) {
$.each(data, function(key, val) {
allslides[key] = { image : val.image, title: val.title, desc:val.desc };
});
slider();
});