backbone.js如何用整个数据库表填充集合

时间:2012-09-07 12:53:29

标签: backbone.js backbone.js-collections

我已经定义了ModelCollection,因为我的数据库中已有记录,所以我希望在页面加载时显示应用程序上的所有记录。

我尝试使用Backbone.sync,但我仍然在Chrome调试模式下看到一个空集合。

My Backbone.js代码:

http://jsfiddle.net/GhaPF/15/(由于模板依赖性,我不得不删除一些代码)。

$(document).ready(function() {

    var Item = Backbone.Model.extend({
        defaults: { "date": "",
                    "text": "default text"
                },
        initialize: function() {      // STEP 3
            var dateString = giveMeDate();
            this.set("date", dateString);
        },
        urlRoot : './items'
    });

    var ItemList = Backbone.Collection.extend({
        model: Item,
        url: './items/',
        initialize: function() {
            this.fetch();
        }
    });


   //************ VIEW ********************************
    var ItemListView1 = Backbone.View.extend({
        el: 'body',
        initialize: function(myitemList) {
            this.itemlist = myitemList;
            this.itemlist.bind('add', this.addOneItem, this);
            this.render();
        },
        addOneItem: function() {
            this.render();
        },
        render: function() {                // STEP 5       this is called because add() is bound to this.render (in initialization of this View)
            text = this.itemlist.toJSON();
            string = JSON.stringify(text);
            $("#view1").html('');
            $.tmpl("itemTemplate", text).appendTo("#view1");
            return this;
        },
        events: {
            "keypress #new-item":  "createOnEnter"    // STEP 1
        },
        createOnEnter: function(e) {
          if (e.keyCode != 13) return;
          if (!$("#new-item").val()) return;
          this.itemlist.create({"text": $("#new-item").val()});   // STEP 2
          $("#new-item").val('');
        }
    });


    $("#new-item").focus();
    var itemlist = new ItemList();
    Backbone.sync("read", itemlist);
    var myitemListView = new ItemListView1(itemlist);

这是我在Backbone.sync之后在集合中看到的内容:

d
_byCid: Object
_byId: Object
length: 0
models: Array[0]
__proto__: x

1 个答案:

答案 0 :(得分:3)

  1. 您可能不应该直接调用sync,因为该方法可能会被其他一些同步方法覆盖(用于支持localStorage,IndexedDB,couchdb或其他)。同步更像是“存储驱动程序”。

  2. 您应该调用fetch来填充您的馆藏。所以在你的代码中,它应该是这样的:

    itemlist.fetch({success: function (models) {
       console.log("got", models);
    });
    var myitemListView = new ItemListView1({collection: itemList});
    
  3. 在页面加载后立即使用异步提取填充您的集合被认为是“糟糕的风格”。您通常应该使用与页面一起发送的代码填充它,并且仅使用fetch来对集合进行后续更新。

  4. 在上面的代码示例中,如果您坚持进行异步提取,则可能需要延迟创建视图,直到实际填充集合以避免在列表从空变为填充时出现不必要的闪烁(视图已绑定)到集合,并在获取完成时重置。)