I have defined a Model
and a Collection
, and since I already have records in my database, I wish to show all those records on application on page load.
I tried using Backbone.sync
, but I still see an empty collection in Chrome debugging mode.
My Backbone.js code:
http://jsfiddle.net/GhaPF/15/ (I had to remove some code there because of template dependencies).
$(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);
Here is what I see in the collection after Backbone.sync:
d
_byCid: Object
_byId: Object
length: 0
models: Array[0]
__proto__: x