可能是一个简单的问题...如何在骨干.js视图中访问变量?

initialize: function() { //all init here }
render: function() {//all render here }

printFoo: function(event) {
   var printVar = this.changeFoo.changeVar  // how do I access changeVar  here???
}

changeFoo: function(event) {
  var changeVar = $(e.currentTarget).attr('id');
}


如何访问changeVar?

最佳答案

简短的答案,你不能。

原因:changeVarchangeFoo的私人成员。

您可以提升changeVar成为外部对象的成员。在这种情况下,changeVarinitializerenderprintFoo可以访问changeFoo

function ConstructorFunctionName(){
    var changeVar = 'foo';
    /*this.changeVar = 'foo'; // this can also be used */

    this.initialize = function() { //all init here };
    this.render = function() { //all render here };

    this.printFoo = function(event) {
       var printVar = changeVar;
    };

    this.changeFoo = function(event) {
      this.changeVar = $(e.currentTarget).attr('id');
    };
}


http://jsfiddle.net/Njwdx/

10-07 13:39