[英]Creating multiple instances of gridster within a loop with closures to call same callbacks with different arguments
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. 我目前正在研究基于gridster的CMS模块,这是必需的,以便最终用户创建不同的布局,以多次实例化gridster。
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.
我发现这似乎与我需要的东西相似,但是不幸的是,我对coffeescript一无所知,并且从'do'的coffescript文档( coffescript.org )中,我看不到我在做什么错。 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. 尝试在stop函数的循环和定义中使用不同于i的其他变量名。 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.
还用var循环定义i,引用不带var的变量/属性会使它成为全局变量。
What is the purpose of the var keyword and when to use it (or omit it)? var关键字的目的是什么?何时使用(或省略)?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.