Is there a more readable way of expressing javascript closure?
I would like to update some data with JSON when the user clicks on the object. I came up with the following double closure.
var buildGetJSON = function(m,t,p,u) {
return function () {
var buildUpdateParticipants = function(m,t,p) {
return function(data) { updateParticipants(m,t,data,p); };
};
$.getJSON(u, buildUpdateParticipants(m,t,p));
};
};
marker.on("click", buildGetJSON(marker, title, popmsg, url));
This works, but made me wonder if there is a more concise way to put this in than by writing a closure variable for the two function calls. Any hints?
source to share
Yes, the second close is redundant.
function buildGetJSON(m,t,p,u) {
return function() {
$.getJSON(u, function(data) {
updateParticipants(m,t,data,p);
});
};
}
marker.on("click", buildGetJSON(marker,title,popmsg,url));
If you only use buildGetJSON once, you can simplify it even further by making the buildGetJSON function anonymous.
marker.on("click", function(m,t,p,u) {return function() {
$.getJSON(u, function(data) {
updateParticipants(m,t,data,p);
});
};}(marker,title,popmsg,url));
Here's another way to do it completely with anonymous functions. It doesn't collapse over multiple lines, but I think it looks a little clearer.
!function(m,t,p,u) {
marker.on("click", function() {
$.getJSON(u, function(data) {
updateParticipants(m,t,data,p);
});
});
}(marker,title,popmsg,url);
source to share
Why not just do it?
marker.on("click", function () {
$.getJSON(url, function (data) {
updateParticipants(marker, title, data, popmsg);
});
});
Looks much more synoptic - at least to me :-)
But keep in mind: if variables marker
, title
etc. may change and you don't want it, you need additional closure. For example. if you call this, for example, in a loop, and the variable marker
(or other variables) is changing through the loop! Then you need to wrap the code in another closure in a loop:
for (marker in markers) {
(function (marker) {
// above code
})(marker);
}
Closures are a very nice and very powerful JavaScript property once you know how to use them. Watch the video "The JavaScript Programming Language" by Douglas Crockford, they explain it in a great way.
source to share