Backbone.js中的变量范围

时间:2013-06-07 12:37:58

标签: javascript backbone.js scope

我在Backbone.js中使用Stripe支付系统。

这是模型代码的一部分:

App.Models.Payment = Backbone.Model.extend({

defaults: {
    id:null
},

url: function() {
    // code
},

initialize:function(){      
    this.id='';
    this.saveClicked= false;
    this.saveDetailsChecked= true;
}

此视图中使用此模型:

App.Views.BillingView = Backbone.View.extend({

el: '#billing-fields',

events: {
    'click #billing-footer-buttons .navigation .confirm-btn': 'saveCardClicked'
},

initialize:function(models, options) {
    Stripe.setPublishableKey('**********************');
    var self = this;
},

saveCardClicked:function(e) {
    e.preventDefault(); 
    if (this.model.saveClicked) return false;
    this.model.saveClicked = true;
    var $form = $('#payment-form');
    Stripe.createToken($form, this.stripeResponseHandler);
},

cancelClicked:function() {
    vent.trigger('showScreen', 'subscribe-container');
},

stripeResponseHandler:function(status, response) {
    var $form = $('#payment-form');
    self.saveDetailsChecked = document.getElementById("billing-checkbox").checked;
    var atr1 = document.getElementById("billing-card-number").value;
    var atr2 = self.model.savedCard;
    if(document.getElementById("billing-card-number").value == self.model.savedCard){
        self.model.set('use_saved_card','1');
        vent.trigger('doPayment');
    }else{
        if (response.error) {
            // code
        } else {
            // code
        }
    }
    self.saveClicked = false;
}
});

在saveCardClicked函数中,我能够从模型中访问变量,例如saveClicked变量。

但是在stripeResponseHandler中我无法从模型中访问'saveClicked'变量,在这个函数中它引用了window,并且也无法访问在initialize函数中定义的自变量。

从Stripe API调用stripeResponseHandler。

有没有办法可以访问stripeResponseHandler函数中的savedCard变量,或者我应该使用全局变量?

2 个答案:

答案 0 :(得分:1)

尝试使用它: -

Stripe.createToken($form, this.stripeResponseHandler.bind(this));

答案 1 :(得分:1)

当然,您可以使用bind

绑定通过将参数绑定到某个函数调用来工作,并且将返回一个函数,该函数在被调用时将传递您在调用bind时声明的参数(实际上,您未声明的任何其他预期参数) )。有一个特殊参数传递给bind。第一个,它是调用函数时将使用的this对象。

那么,你要做的就是致电

Stripe.createToken($form, this.stripeResponseHandler.bind(this));

这里你宣布一个回调(stripeResponseHandler),当被调用时,this作为this对象(我知道这个短语是错综复杂的,但我认为你得到了它。)

另外,请记住您的行

var self = this;

不能正常工作,因为它的范围是initialize函数,因此在其外部不可见。