Reputation: 2383
I am new in Backbone and trying to run following code. But I don't understand somehow. It is not working properly. More clearly when I create collection listenTo doesn't catch the create event.
Here is my code
var levelIndex=0;
var app = {};
$(function(){
$('.datepicker').datepicker({
format: 'dd/mm/yyyy',
startDate: '-3d'
});
//model
app.Level = Backbone.Model.extend({
defaults: {
levelIndex:-1
}
});
//collection
app.Levels= Backbone.Collection.extend({
model: app.Level,
url:'#'
});
//views
app.LevelView = Backbone.View.extend({
events: {
'click .addItems': 'addItems',
'click .clearItems': 'clearItems',
'click .removeLevel':'removeLevel'
},
addItems: function () {
// add items
},
clearItems:function(){
//
},
removeLevel:function(){
//
},
tagName: 'div',
className: 'level active',
template: _.template($('#levelTemplate').html()),
render: function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
//levels view
app.LevelsView = Backbone.View.extend({
events: {
'click .add': 'addLevel'
},
addLevel: function( e ) {
e.preventDefault();
console.log('inside add level function');
var formData = {};
formData['levelIndex']=levelIndex++;
this.collection.create( formData );
console.log('after creating collection');
},
el: '#levels',
initialize: function() {
this.collection=new app.Levels(new app.Level());
//following line of code doesnt work properly
this.listenTo( this.collection, 'create', this.renderLevel );
},
// render levels view by rendering each level in its collection
render: function () {
this.collection.each(function (item) {
this.renderLevel(item);
}, this);
},
// render a level by creating a LevelView and appending the
// element it renders to the levels' element
renderLevel: function (item) {
var levelView = new app.LevelView({
model: item
});
this.$el.append(levelView.render().el);
}
});
new app.LevelsView();
});
Upvotes: 0
Views: 306
Reputation: 1869
There is no event create
on collection or model.
In your case you want to use event add
that fire when model added to collection.
But you'll miss one model adding, because you added first model before start listening.
http://backbonejs.org/#Events-catalog
About Collection.create()
:
Creating a model will cause an immediate "add" event to be triggered on the collection, a "request" event as the new model is sent to the server, as well as a "sync" event, once the server has responded with the successful creation of the model. Pass {wait: true} if you'd like to wait for the server before adding the new model to the collection.
Upvotes: 3