javascript - 如何使用主干将 'this' 传递给事件?

标签 javascript backbone.js

我有一个将函数绑定(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/

相关文章:

javascript - JQuery 即时添加类或隐藏类

javascript - 获取另一个div中的span内容

javascript - 在 jQuery 中合并对象,具有 $.extend 函数的相反效果

javascript - 客户端调用的 api 方法内的 HTTP GET

backbone.js - Backbone 收集比较器

javascript - 未捕获的类型错误 : Cannot call method 'replace' of undefined underscore. js

javascript - babel 与express js :avoid relative path imports

javascript - 如何在主干中实现 Angular 样式指令?

php - PHP中无法获取 'http put'内容

javascript - 使用 Devise 覆盖 Backbone.sync 以进行 Rails API 身份验证