【问题标题】:How to use params from within a success callback function (Backbone)如何在成功回调函数 (Backbone) 中使用参数
【发布时间】:2013-07-01 13:21:04
【问题描述】:

我尝试在成功回调函数中设置的参数似乎有问题:

var CampModel = CampDataModel.extend({

    initialize : function(){

        this.fetchActiveAndPending();
        console.log(this.get('active'));
    },

    //Counts active and pending campaigns for front page.
    CountActiveAndPending : function(data){
      var active = 0;
      var pending = 0;

      $.each(data.returnValue,function(index,val){
        if (val.ApprovedOnSite){
          active++;
        }
        else
          pending++;       
      });
      this.set('active',active);
      this.set('pending',pending);
    },

    //fetches  data from server using campModel.
    fetchActiveAndPending : function(){
      console.log('fetching!');
      that = this;
     this.fetch({
        success:function(model,response){
          that.CountActiveAndPending(response);        
        }

      });
       }
    });

    return CampModel;
});

this.get('active') 的结果始终是默认数字。如果我尝试在成功回调函数中使用 this.get('active') ,它会给出正确的结果。是否可以从回调函数中设置一个 var 并从外部调用它,比如说初始化函数?

【问题讨论】:

    标签: javascript backbone.js backbone-relational


    【解决方案1】:

    这不是闭包的问题(意味着您的变量无法从您的回调函数或类似的奇怪的东西中访问),而是执行时间的问题。当客户端从服务器获得响应时,您的 success 回调将异步执行。确保响应已到达的唯一方法是使用侦听器 (http://backbonejs.org/#Events) 或回调(作为您的成功函数)。如果您确保在收到响应之后执行部分代码,那么您的active 参数将具有正确的值。

    当你这样做时:

    console.log(this.get('active'));
    

    请求仍处于待处理状态,因此active 仍等于-1。所以您的问题仍然是您没有考虑代码的异步方面。

    【讨论】:

    • 在这里与我无关 :) 没有在成功回调中运行函数确保响应返回?
    • @Yuval 好吧,它至少可以确保它成功返回,但您之前仍在运行console.log
    • 明确地说,您在调用之前定义了回调,但在收到响应后它仍然运行。
    【解决方案2】:

    我同意@Loamhoof,您有时间问题,一种解决方案是:

    initialize : function(){
      this.fetchActiveAndPending(function() {
          console.log(this.get('active'));
      });
    },
    
    CountActiveAndPending : function(data){
      ...
    },
    
    fetchActiveAndPending : function(completeFn){
      console.log('fetching!');
      var _this = this;
      this.fetch({
        success:function(model,response){
          _this.CountActiveAndPending(response);
          completeFn();
        }
    
      });
    }
    

    附言感谢@Loamhoof 挑战我之前的假设并提供了一个例子。

    【讨论】:

    • 你不传递上下文,它很丑陋,而是你绑定它:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…underscorejs.org/#bind。另外,他已经在使用that,所以上下文不是问题。
    • @Loamhoof 我同意你的观点,传递上下文是一个坏主意,我只是想通过解释的方式提供第二个选项(尽管这不是很清楚)。 Bind 也可以,只是语法偏好的问题。当然,问题仍然存在,this 的值已经改变(即使在使用它来调用函数时),所以您需要使用 .call() 或 .bind()。因此,这不是时间问题。
    • @Loamhoof,你说得对,为什么他的 console.log() 语句在 initialize() (时间问题)中不起作用,这是与我所描述的不同的问题(这个值在 CountActiveAndPending()) 中。这两项更改都是必要的。
    • 我建议你看看jsfiddle.net/j9mDF。情况是一样的。回调中的上下文不一样,但是调用that的方法后会是他的对象。
    • 此外,如果他有上下文问题,会抛出Object window does not have a method set 或类似的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 2017-01-15
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多