2013-07-26 58 views
3

使用骨干收集从JSON服务的集合,我已经使用视图INITIALISE激活取,但是我现在想通过JSON阵列回到看法,但我米不能确定如何实现这一目标?传递骨干读取/初始化的变量视图

下面的代码是什么我目前使用:

app.AppView = Backbone.View.extend({ 

     initialize: function(){ 


      // Instanciate a new Form collection (which is derrived from the input model) 
      var inputs = new app.Form(); 

      // Perform a GET on the model url to the service 
      inputs.fetch({ 

       success: function() { 

        var questions = inputs.get(0).toJSON().Questions; 

        console.log(questions); 



       }, // End Success() 

       error: function(err){ 
        console.log("Couldn't GET the service " + err); 
       } 

      }); // End Input.fetch() 

      this.render(); 

     }, // End Initialize 

     render: function(){ 
      el: $('#factfinder') 
      var template = _.template($("#form_template").html(), {}); 
      this.$el.html(template); 

     } 

    }); // End AppView.Backbone.View.extend() 

回答

0

你通常不会通过JSON来render,而是集model。此外,您还需要调用rendersuccess回调里面,因为获取是异步的:现在

// store a reference to the view object 
var self = this; 

inputs.fetch({ 
    success: function() { 
     var questions = inputs.get(0).toJSON().Questions; 
     console.log(questions); 
     this.model = new Backbone.Model(questions); 
     self.render(); 
    }, // End Success() 
    error: function(err){ 
     console.log("Couldn't GET the service " + err); 
    } 
}); // End Input.fetch() 

render,您可以从模型得到的JSON回来:

this.$el.html(template(this.model.toJSON())); 

这似乎是这样做的一种迂回的方式 - 从构建JSON的模型,然后拿到JSON从模型回来。但这是设计。它允许模型有机会做它的事时,设置它任何违约和验证来从服务器返回的原始数据。

1

首先fetch是异步的。因此,当请求从服务器返回时,您总是需要调用渲染器。最好的办法,可以听resetsync事件的服务器上并调用渲染方法。

app.AppView = Backbone.View.extend({ 
     el: $('#factfinder'), 
     initialize: function() { 

      var inputs = new app.Form(); 

      // Listen top the events that calls the success method 
      this.listenTo(inputs, 'sync reset', this.renderView); 
      // to bind the this context 
      _.bindAll(this, 'renderView'); 
      // Perform a GET on the model url to the service 
      inputs.fetch({ 
       error: function(err){ 
        console.log("Couldn't GET the service " + err); 
       } 
      }); // End Input.fetch() 

     }, // End Initialize 
     renderView: function() { 
      var questions = inputs.get(0).toJSON().Questions; 
      console.log(questions); 
      // Call render when the request comes back with response 
      this.render(); 
     }, 
     render: function(){ 
      var template = _.template($("#form_template").html(), {}); 
      this.$el.html(template); 
     } 

    }); // End AppView.Backbone.View.extend() 

和你有语法错误里面的渲染方法

el: $('#factfinder') 

应该是

var el = $('#factfinder') 

或者你可以把它移到外面渲染