I'm currently working on a gridster based CMS module and it's required, to let the final user create different layouts, to instantiate gridster multiple times.
My problem comes up when I loop through the number of grid which should be set and I try to define callbacks which should be called with different arguments based on the iteration in which they get defined: when I test them it seems they inherit the (last) same value.
I think that's a closure matter and I'm trying to work that out even reading several posts from this forum but with no success and I appreciate a lot if someone could gimme a hint to take the right track..
here is my code:
var gridster= [];
var id_layouts = [];
$(".selectedLayout").each(function(){
id_layouts.push($(this).val());
});
for(i=0; i<id_layouts.length; i++){
makeGridster(i, id_layouts[i]);
}
function makeGridster(index, id_layout){
gridster[index] = $('#blockcompositeGrid'+id_layout+' > ul').gridster({
widget_margins: [10, 10],
widget_base_dimensions: [100, 100],
draggable:{
stop: function(){
return function(i, l){
updateSerialization(i, l)
}(index, id_layout)
}
}
}).data('gridster');
}
function updateSerialization(index, id_layout){
console.log(index, id_layout);
}
The grids get built, that's ok. As you can see I'm trying to call a function as callback of the drag action stop and that should be called with different arguments. I've found this which seems to be similar to what I need, but unfortunately I don't know anything about coffeescript and from the coffescript documentation for 'do' (coffescript.org) I cannot see what I'm doing wrong. Thank you in advance for any help
Try using a different variable name other than i in the loop and definition of the stop function. Due to scoping they may be stepping on each other. Also define i in loop with var, referencing a variable/property without var makes it global.
What is the purpose of the var keyword and when to use it (or omit it)?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for