2016-02-16 52 views
0

我正在为此项目使用dojo工具包。我有一个下拉按钮,其中有一个菜单作为一个孩子,然后有各种菜单项。由于这将是一个“生活”的应用程序,菜单项将随着业务增长而改变。我的目标是能够为菜单中包含的所有菜单项创建事件监听器。 Dojo提供了一个访问器函数“getChildren()”,用于生成我想循环遍历的所有菜单项的对象。该菜单项有一个标签和ID,我希望能够使用,如果当该项目被选中。 (注:按钮,菜单和菜单项被另一脚本包含但全局存储在数组中命名的布局,以同样的方式予追加功能和瓦尔到主= []波纹管。)JavaScript - 动态创建事件监听器

main = []; 


require([ 
"dojo/dom","dojo/on","dojo/parser","dojo/json","dojo/domReady!" 

], function(dom,on,parser,JSON) { 

parser.parse(); 

console.log("Main Start"); 

//flags 

//Listeners 

var gpMenuChildren = layout.gpMenu.getChildren(); 
for (i in gpMenuChildren) { 
    var id = gpMenuChildren[i].id; 
    var label = gpMenuChildren[i].label; 
    console.log(label); 
    console.log(id); 
    on(dom.byId(id),"click",function() { 
     console.log("dom node w/ 'id' of " + id +" was clicked!"); 
     layout.gpButton.set("value",label); 
     main.updateQueryStr(); 

    }); 
} 

main.updateQueryStr = function updateQueryStr() { 
    console.log("updateQueryStr called..."); 
    layout.cpCentTop.set("content", "Test updateQueryStr"); 
}; 


console.log("Main End"); 

}); 

通过console.log()我可以确认个人的ID和标签是正确的,我们可以通过这种方法成功地循环通过孩子。

这里的问题是

的事件侦听器成功地连接到所述菜单列表的每个项目,然而收听者的功能成分似乎被重写每次并且因此只需要对属性(ID和标签)循环中的最后一个孩子。换句话说,点击时每个菜单项都记录相同的ID和标签值。

任何想法,以确保创建独立的事件监听器,可以包含从儿童适当的值?

提前致谢!

+1

虽然使用'this'解决您的问题,了解您所面临哪根,请阅读[JavaScript的闭包内环路 - 简单实用的例子(http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Teemu

回答

0

发生这种情况是因为变量的内容发生变化。您可以检索的ID,并直接从对象标签,使用this

console.log("dom node w/ 'id' of " + this.id +" was clicked!"); 
     layout.gpButton.set("value",this.label); 
+0

this.id返回正确的id,但this.label返回undefined。这对我来说很奇怪,因为声明“var label = gpMenuChildren [i] .label;”正确返回,就像“var id = gpMenuChildren [i] .id;”也不应该。标签部分不应该与“id”部分相同吗? – LCaraway

+0

尝试twith'this.getAttribute(“label”)' – Juan

0

之所以能够通过传递变量从我的循环到一个外部函数,然后做什么它需要解决的封锁和范围的问题与数据(创建一个事件监听器)。

main.createListener = function createListener (id,label) { 
    console.log("createListener called..."); 
    on(dom.byId(id),"click", function() { 
     console.log("dom node w/ 'id' of " + id +" and a label of " + label + " was clicked!"); 
     layout.gpButton.set("value",label); 
     main.updateQueryStr(label); 
     }); 
    }; 

    var gpMenuChildren = layout.gpMenu.getChildren(); 
    for (i in gpMenuChildren) { 
     var id = gpMenuChildren[i].id; 
     var label = gpMenuChildren[i].label; 
     main.createListener(id,label); 
    }