2013-01-18 62 views
0

我有一個骨幹收集。我拿。服務器返回一個JSON。我如何使用新數據填充集合?這是我的代碼:骨幹收集人口與服務器數據

var Todos = Backbone.Collection.extend({ 

     url: "server/todos-service.php", // this does what it is supposed to do so no worries! 

     model: Todo, 

     initialize: function(attributes, options) {  
      // IN HERE WHAT DO I HAVE TO DO? 
      // WHAT EVENT SHALL I BIND TO TO REACT THE DATA DELIVERY? 
      // AND WHAT SHALL I DO NEXT TO POPULATE THE DAMN THINGS 

      } 
     }); 

    // CLIENT CODE 
    new Todos().fetch(); 

有誰能告訴我這是應該怎麼辦?

乾杯

回答

1

fetch將啓動Ajax調用服務器。當數據返回時,它會自動將數據放入您的集合中,並且集合將觸發一個reset,就像「我已完成讀取數據bro,您現在可以使用它」。

您通常會從您的視圖中調用fetch(),並讓視圖監聽reset事件。重置事件觸發時,視圖呈現集合。

var Todo = Backbone.Model.extend({ 
    // my model 
}); 

var TodoList = Backbone.Collection.extend({ 
    url: myurl 
    model: Todo 
    // my collection (usually nothing in the initialize function) 
}); 


var AppView = Backbone.View.extend({ 
    initialize: function() { 
    // instantiate the collection 
    this.collection = new TodoList(); 

    //listen to the reset event on the collection. When the reset event trigger, call the render function. 
    this.collection.on('reset', this.render, this); 

    // get the data from the backend 
    this.collection.fetch(); 
    }, 
    render: function() { 
    // render the collection like a boss 
    } 
}); 

//instantiate the view 
var App = new AppView; 

同樣作爲一種資源,我發現這個教程是真正有助於理解骨幹http://net.tutsplus.com/sessions/build-a-contacts-manager-using-backbone-js/

+0

我同意,我從來沒有做到這一點的基礎知識,但多數民衆贊成什麼大多數爲待辦事項例子簡單的緣故。我想我會更新它haha – hajpoj

+0

我看到... ...「重置」是no1完美的不良事件名稱... – nourdine