2012-08-22 33 views
2
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变量响应的价值......但它的未来“未定义”。任何想法,我错了?取结果是不确定的(Backbone.js的)

+0

有了这些信息,我可以推断出大量的问题。服务器是否返回正确的json? 'fetch'后服务器是否返回任何东西?你是否在'success'回调中尝试'console.log(arguments)'来确保你正在接收多个参数? – Deeptechtons

回答

5

fetch方法是异步的,所以output变量在您使用它时不会被分配。尝试把render调用成功回调,而不是内部:

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

谢谢..dbaseman ...它的工作 –

0

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