egi*_*dra 3 javascript backbone.js
我有一个事件将函数绑定到单击.单击会在同一视图中调用另一个函数.不幸的是,范围不是正确的范围.当我尝试执行此.otherFunction()时,分配给click的函数与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());
},
Run Code Online (Sandbox Code Playgroud)
这些都属于同一观点.
编辑:嗯,现在的问题是我得到这个错误:未捕获的TypeError:对象[对象DOMWindow]没有方法'renderLeaveGoal'.这似乎是我保存了错误的范围吗?
标准技术是做类似的事情
var self = this;
Run Code Online (Sandbox Code Playgroud)
那你可以做
self.otherFunction();
Run Code Online (Sandbox Code Playgroud)
代替
this.otherFunction();
Run Code Online (Sandbox Code Playgroud)