我有一个将函数绑定(bind)到点击的事件。单击调用同一 View 中的另一个函数。不幸的是,范围不是正确的范围。当我尝试执行 this.otherFunction() 时,分配给点击的函数与 this.otherFunction() 不在同一范围内。有没有办法传入 otherFunction() 的作用域?
initialize: function() {
this.render();
if (joinedGoalList.get(this.model.id) != null) {
this.renderLeaveGoal();
} else {
this.renderJoinGoal();
}
},
events: {
"keypress #goal-update": "createOnEnter",
"click #join-goal": "joinGoal",
"click #leave-goal": "leaveGoal",
},
joinGoal: function() {
matches = joinedGoalList.where({id: this.model.get("id")});
if (matches.length == 0) {
joinedGoalList.create({goal_id: this.model.get("id")}, {wait: true, success: function() {
var self = this;
self.renderLeaveGoal();
}, error: function() {
console.log("error");
}});
}
},
renderLeaveGoal: function() {
console.log("render leave goal");
var template = _.template($("#leave-goal-template").html());
console.log(template);
$("#toggle-goal-join").html(template());
},
这些都在同一个 View 下。
编辑: 嗯,现在的问题是我得到了这个错误: 未捕获的 TypeError:对象 [object DOMWindow] 没有方法“renderLeaveGoal”。这似乎是我保存了错误的范围?
最佳答案
标准技术是做类似的事情
var self = this;
然后你可以做
self.otherFunction();
代替
this.otherFunction();
关于javascript - 如何使用主干将 'this' 传递给事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10255558/