【问题标题】:fetch result is undefined (Backbone.js)获取结果未定义(Backbone.js)
【发布时间】:2012-08-22 06:43:27
【问题描述】:
var ListView = Backbone.View.extend({
    el: $('hello'),
    initialize: function() {
        var stuff = new FieldCollection();
        var output;
        stuff.parse();
        stuff.fetch({
            success: function (collection, response) {
                console.log(response);
                output=response;
                return response;
             }
        });
        this.render(output);
   },
   render:function(output){
        console.log(output);
        $(this.el).append("<button id='add'>hiii</button>");
        $(this.el).append("<button id='removeAll'>Remove all list item</button>");
    }
});

在这里,我试图在output 变量中捕获响应的值...但它出现了“未定义”。有什么想法我弄错了吗?

【问题讨论】:

  • 有了这些信息,我可以推断出很多问题。服务器是否返回正确的 json?服务器在fetch 之后是否返回任何内容?您是否尝试在success 回调中尝试console.log(arguments) 只是为了确保您接收到多个参数?

标签: javascript asynchronous backbone.js callback


【解决方案1】:

fetch 方法是异步的,所以 output 变量在您使用时不会被赋值。尝试将 render 调用放在成功回调中:

var self = this;
stuff.fetch({
        success: function (collection, response) {
            console.log(response);
            output=response;
            self.render(output);
            return response;
         }
    });

【讨论】:

    【解决方案2】:

    考虑到您的设置,dbasemans 解决方案是正确的。但是,我宁愿将事件处理程序绑定到“重置”事件。这需要在获取之前发生。这更简洁,也适用于稍后在应用程序运行时进行的进一步提取。

    【讨论】:

      猜你喜欢
      • 2013-08-29
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 2012-07-18
      • 1970-01-01
      • 2015-03-23
      相关资源
      最近更新 更多