My.Awesome.Obj = function() {
return {
// PUBLIC PROPERTIES
legendObj: null,
// PUBLIC METHODS
init: function() {
this.assignLegendClick();
},
assignLegendClick: function() {
console.log('*** drawLegend()');
var checkboxes = this.legendObj.find("input");
checkboxes.each(function() {
$(this).click(function() {
this.handleLegendClick();
});
})
},
handleLegendClick: function() {
console.log('*** handleLegendClick()');
},
EOF: null
};
}();
所以我收到错误说
未定义handleLegendClick
我假设这是一个范围问题,但我不确定如何在循环中引用回父对象......
答案 0 :(得分:3)
问题是调用click事件处理程序时this
是window
。
您可以这样做:
My.Awesome.Obj = function() {
var obj = {
// PUBLIC PROPERTIES
legendObj: null,
// PUBLIC METHODS
init: function() {
obj.assignLegendClick();
},
assignLegendClick: function() {
console.log('*** drawLegend()');
var checkboxes = obj.legendObj.find("input");
checkboxes.each(function() {
$(this).click(function() {
obj.handleLegendClick(); // <=== replace this with obj
});
})
},
handleLegendClick: function() {
console.log('*** handleLegendClick()');
},
EOF: null
};
return obj;
}();
答案 1 :(得分:2)
是的,这是一个范围问题:
assignLegendClick: function() {
console.log('*** drawLegend()');
var checkboxes = this.legendObj.find("input");
checkboxes.each(function() {
$(this).click(function() {
this.handleLegendClick();
});
})
使用帮助程序参数来保留范围(通常称为self或_self)
assignLegendClick: function() {
console.log('*** drawLegend()');
var self = this
, checkboxes = this.legendObj.find("input");
checkboxes.each(function() {
$(this).click(function() {
self.handleLegendClick();
});
})