骨干视图范围问题

时间:2013-09-09 21:21:05

标签: javascript backbone.js

我很确定这是一个范围问题,但我有一个骨干视图,它使用Bootbox(一个扩展twitter的Bootstrap的小型库)在将模型保存到数据库之前提示确认。该视图负责捕获SAVE按钮单击,此时应弹出Bootbox对话框并提示确认。见下文:

    window.StartView = Backbone.View.extend({

    initialize: function () {
        this.render();
    },  

    events: {
        "click .nextstage"   : "nextstage",
        "click .reshuffle"   : "render",
        "click .drilldone"   : "drilldone"
    },  

    drilldone: function() {

      bootbox.confirm("Record Results?", function(result) {

      result ? this.saveResults : alert("canceled") ;

    }); 

    },

问题是this.saveResults永远不会运行。我尝试用“alert(this)”代替它,然后我找回了“Window”,因为Bootbox库是在主HTML文档中定义的。那么如何获取Bootbox调用然后回调我的View的saveResults方法呢?我必须以某种方式将方法的引用传递给Bootbox确认方法吗?

2 个答案:

答案 0 :(得分:1)

只需将上下文置于变量中,然后调用该函数。 (没有括号()它将无法运行)

drilldone: function() {
    var self = this;

    bootbox.confirm("Record Results?", function(result) {

        result ? self.saveResults() : alert("canceled") ;

    }); 

},

Javascript使用范围链来建立给定函数的范围。当您创建一个函数时,您创建一个新的作用域,并且此作用域可以访问在其父项中声明的每个变量以及在其父项上声明的每个变量(将其视为范围链一直向上直到全局范围)。

如果没有设置thisthis将成为global对象(浏览器中为window)。您可以使用thiscallapply动态更改bind函数的值。这就是jQuery在其大部分回调中所做的事情(这可能就是为什么你选择窗口是this - 但这是无关的)。

通过分配var self = this,您可以将引导框回调作用域中可用的this对象作为变量引用。

这是非常清晰的概述。您可能有兴趣阅读其他stackoverflow答案:What is the scope of variables in JavaScript?

还有一本名为JavaScript Enlightment的免费书正在触及这个主题。

答案 1 :(得分:0)

我从未使用过Backbone,但这看起来并不像Backbone特定的那样,而是你提出的一个范围问题。我试试:

window.StartView = Backbone.View.extend({

  initialize: function () {
      this.render();
  },  

  events: {
      "click .nextstage"   : "nextstage",
      "click .reshuffle"   : "render",
      "click .drilldone"   : "drilldone"
  },  

  drilldone: function() {
    var ctx = this;
    bootbox.confirm("Record Results?", function(result) {
    result ? ctx.saveResults : alert("canceled") ;
  }); 
},

这有点不理想,因为重新分配这个有点内存泄漏,但影响很可能是微不足道的。

相关问题