【问题标题】:Creating multiple instances of gridster within a loop with closures to call same callbacks with different arguments在带有闭包的循环中创建多个 gridster 实例以调用具有不同参数的相同回调
【发布时间】:2014-01-22 21:57:49
【问题描述】:

我目前正在开发一个基于 gridster 的 CMS 模块,它需要让最终用户创建不同的布局,多次实例化 gridster。

当我遍历应该设置的网格数量并且我尝试根据定义它们的迭代定义应该使用不同参数调用的回调时,我的问题出现了:当我测试它们时,它们似乎继承了(最后一个)相同的值。

我认为这是一个关闭问题,我正在努力解决这个问题,即使阅读了这个论坛的几篇帖子,但没有成功,如果有人能给我一个提示,让我走上正确的道路,我将不胜感激..

这是我的代码:

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);

    }

网格已构建,没关系。 如您所见,我正在尝试调用一个函数作为拖动动作停止的回调,并且应该使用不同的参数调用该函数。 我发现this 似乎与我需要的相似,但不幸的是我对coffeescript 和'do' 的coffescript 文档一无所知(coffescript.org)我看不出我做错了什么. 提前感谢您的任何帮助

【问题讨论】:

    标签: javascript jquery loops closures gridster


    【解决方案1】:

    尝试在循环和停止函数的定义中使用除 i 之外的其他变量名。由于范围界定,他们可能会互相踩踏。还可以用 var 在循环中定义 i,引用不带 var 的变量/属性使其成为全局变量。

    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

    【讨论】:

    • 感谢您的回复,虽然没有解决问题,但这些都是很好的建议
    猜你喜欢
    • 2014-12-28
    • 2021-09-24
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    相关资源
    最近更新 更多