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();

谁能告诉我这应该怎么做?

干杯

4

1 回答 1

1

fetch将启动对您的服务器的 ajax 调用。返回数据后,它会自动将数据放入您的集合中,并且该集合将触发reset类似“我已完成获取数据,兄弟,您现在可以使用它”的信息。

您通常会从视图内部调用 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/

于 2013-01-18T10:11:39.070 回答