我正在构建一个小应用程序,这是销售咨询过程的一部分。它有“页面”,访问者通过这些页面。我已经将这些页面作为大型对象文字的一部分进行了布局。在下面的代码中,branch-select就是其中之一。如您所见,init()函数通过使用this来引用parent branch-select来设置同级值。但是,save()函数是从click事件中调用的,因此,与其使用this,我似乎每次都要费力地写出完整的对象引用来设置值?请参阅下面的代码和评论来说明这个问题:
// This is part of a larger object called "stepData"
"previous page": {
// ...
}
"branch-select": {
ref: "Select Type",
visited: false,
init: function(){
this.visited = true; // Here I can use "this" to set other values in the parent object
// ....
},
next: "",
save: function(){
branchKey = $(this).attr('data-value'); // this function is invoked from a click event, so "this" refers to the DOM element that was clicked. Therefore throughout the rest of the function if I want to set values on the parent object, I have to write out the full object reference each time...
switch(branchKey){
case "Lodges":
stepData['branch-select'].ref = "Lodges";
stepData['branch-select'].values[0].a = "Lodges";
stepData['branch-select'].next = "lodge-2"; // Do I really have to write out stepData['branch-select'] each time?
break;
case "Caravans":
stepData['branch-select'].ref = "Caravans";
stepData['branch-select'].values[0].a = "Caravans";
stepData['branch-select'].next = "van-2";
break;
}
stepData[stepData['branch-select'].next].init();
}
},
"next page": {
// ...
}为了DRY (不要重复自己)代码的利益,我想知道这是否有任何简洁的解决方案?
编辑:
Webkit的答案提出了一个新的问题;动态引入了单击的DOM元素(.分支-选择),因此要绑定click事件,我必须使用:
$("#template-holder").on('click', ".branch-select", stepData['branch-select'].save);(模板持有者是始终存在的父元素)。如何将call()方法集成到上面的代码中?
发布于 2014-09-14 13:38:11
在处理事件时,另一种让“此”引用对象的方法是使用'call‘。
例如:
var setData = {
save: function(){
// 'this' shall be setData!
var _bs = this['branch-select'];
_bs.ref = "Lodges"...
}
}然后:
$(".someElement").on('click', function() {
setData.save.call(setData)
});**更新(我敢肯定这也应该是一样的):
$("#template-holder").on('click', ".branch-select", function() {
stepData['branch-select'].save.call(setData)
});https://stackoverflow.com/questions/25833470
复制相似问题