Backbone.js CollectionView not rendering html - backbone.js

I'm kind of new to Backbone. I'm stuck and I can't find the bug that prevents this code from rendering the html to the #times_day element. The console.log says that the collection's el is an empty div I don't know why:
TheModel = Backbone.Model.extend({
urlRoot: '/times/api/day_list'
});
DayCollection = Backbone.Collection.extend({
model: TheModel,
url: '/times/api/day_list'
})
DayView = Backbone.View.extend({
tagName: 'li',
render: function(){
return '<h3>' + this.model.get('comments') + this.model.get('minutes') + '</h3>'
}
})
CollectionView = Backbone.View.extend({
initialize: function(){
this.collection.on('reset', this.addAll, this);
},
addAll: function(){
this.collection.forEach(this.addOne, this);
},
addOne: function(dayItem){
var dayView = new DayView({model:dayItem});
dayView.render()
this.$el.append(dayView.el);
},
render: function(){
this.addAll();
}
});
var dCollection = new DayCollection({})
var cView = new CollectionView({collection:dCollection});
dCollection.fetch({
success: function(){
cView.render();
console.log(cView.el);
$("#times_day").html(cView.el);
}
})
Maybe it is a simple bug I can't see.. or maybe it is a more important concept I need to learn. Thanks a lot for your help.

DayView = Backbone.View.extend({
tagName: 'li',
render: function(){
this.$el.html('<h3>' + this.model.get('comments') + this.model.get('minutes') + '</h3>');
}
})
instead returning string in render you should set the html to view's el as you are appending el element in collectionView

Related

Tree view is not rendering in Backbone Marionette

I want to show tree in Backbone Marionette.
For this i create a model
applicationManager.Models.menuItem = Backbone.Model.extend({
initialize: function(){
var
children = this.get('children');
if (children){
this.children = new applicationManager.Collections.menu(children);
this.unset('children');
}
}
});
A collection
applicationManager.Collections.menu = Backbone.Collection.extend({
model: applicationManager.Models.menuItem,
url: '/en/panel/menu'
});
Recursive view
applicationManager.Views.menuItem = Backbone.Marionette.CompositeView.extend({
tagName: 'li',
template: '#menu-template',
initialize: function(){
this.collection = this.model.children;
},
appendHtml: function(collectionView, childView) {
collectionView.$('ul:first').append(childView.el);
},
onRender: function() {
if (_.isUndefined(this.collection)){
this.$('ul:first').remove();
}
}
});
And root view
applicationManager.Views.menu = Backbone.Marionette.CollectionView.extend({
tagName: 'ul',
childView: applicationManager.Views.menuItem
});
My application code is
var
menu = new applicationManager.Collections.menu();
menu.on('reset', function(data){
var
view = new applicationManager.Views.menu({
collection: data
});
applicationManager.getRegion('menuRegion').show(view);
});
menu.fetch({
reset: true
});
But when code is executing, it's no tree structure. Elements follow consecutive from each other.
Can anyone help me?
Best regards, Evgeniy.
The problem was in code for old versions of Marionette.
For now I use this
applicationManager.Views.menuItem = Backbone.Marionette.CompositeView.extend({
tagName: 'ul',
template: '#menu-template',
initialize: function(){
this.collection = this.model.children;
},
attachHtml: function(collectionView, childView){
collectionView.$('li:first').append(childView.el);
}
});
applicationManager.Views.menu = Backbone.Marionette.CollectionView.extend({
childView: applicationManager.Views.menuItem,
});

Backbone appends to list view instead of replacing it

I am producing a single page website with Wordpress and Backbone.js, i have come into a problem with when i fetch new data. It simply adds DOM elements onto the container el rather than replacing them. The collection updates correctly as i can see it has the right amount of elements in the console.
var PostItem = Backbone.Model.extend();
var PostItems = Backbone.Collection.extend({
model: PostItem,
url: '/wp-admin/admin-ajax.php'
});
var postItems = new PostItems();
var PostView = Backbone.View.extend({ /* Model View */
tagName : 'article',
className : 'widget',
template : _.template( $('#widgetPost').html() ),
render: function(){
var attributes = this.model.toJSON();
this.$el.html( this.template( attributes ) );
return this;
}
});
var PostListView = Backbone.View.extend({ /* Collection View */
el : '#content',
initialize: function(){
this.collection.on('add', this.addOne, this);
this.collection.on('reset', this.addAll, this);
},
addOne: function(postItem){
var postView = new PostView({ model : postItem });
this.$el.append( postView.render().el );
},
addAll: function(){
this.collection.forEach(this.addOne, this);
},
render: function(){
this.addAll();
},
});
var postListView = new PostListView({
collection : postItems
});
$(function(){
$('a#posts').click(function(){
postItems.fetch({
data: {
action: 'do_ajax',
fn: 'get_the_posts'
}
});
return false;
});
$('a#pages').click(function(){
postItems.fetch({
data: {
action: 'do_ajax',
fn: 'get_the_pages'
}
});
return false;
});
});
You need to clear out your collectionView's $el! :)
addAll: function(){
this.$el.empty();
this.collection.forEach(this.addOne, this);
}
This should do the trick.

Render not being called in Backbone view

Here is my Backbone:
App.Models.Count = Backbone.Model.extend({
url: this.url,
initialize: function() {
this.fetch({
success: function(data, response) {
this.count = data.get('count');
console.log(this.count); // 9, correct answer
}
});
}
});
App.Views.Count = Backbone.View.extend({
tagName: 'span',
initialize: function(options) {
this.count = this.options.count;
console.log(options); // returns correctly
this.model.on('reset', this.render, this);
},
render: function() {
console.log('test'); // not called
this.$el.html(this.model.toJSON());
return this;
}
});
And in my route:
var mc = new (App.Models.Count.extend({'url' : 'main-contact-count'}))();
var mcv = new (App.Views.Count.extend({ model: mc }))();
console.log(mcv); // 9, correct answer
$('#contactCount').html(mcv);
As you can see, my render method is never called. Also, it seems that my view is being called before my model, based on what I see console.log'd in Firebug. Is that because of the async? Why isn't render being called?
You're using Backbone in a funky way. Here's the more standard way to do this:
App.Models.Count = Backbone.Model.extend({
urlRoot: "main-contact-count"
});
App.Views.Count = Backbone.View.extend({
tagName: 'span',
initialize: function(options) {
this.model.on('change', this.render, this);
},
render: function() {
console.log('test');
this.$el.html(this.model.toJSON());
return this;
}
});
And in the router:
var mc = new App.Models.Count();
var mcv = new App.Views.Count({model: mc});
mc.fetch();
$('#contactCount').html(mcv.el);
EDIT
It turns out you're listening to "reset" on a Backbone model. This will never happen. Try listening on "change" instead of reset:
this.model.on('change', this.render, this);

Super simple-minimal Backbone script requested

Looking for the absolute minimum script to get Backbone working. Tried piecing various tutorials and sample together, but having problems getting views to work. Nothing fancy, I'll take raw json in the browser right now. Just a basic skeleton to help connect the dots and build on. I've tried various variations on the following:
(function ($) {
var model = Backbone.Model.extend({
idAttribute: 'custId'
});
var collection = Backbone.Collection.extend({
initialize: function(){
},
model: model,
url: '/cust'
});
var view = Backbone.View.extend({
initialize: function(){
_.bindAll(this, 'render'); // fixes loss of context for 'this' within methods
this.collection.bind("reset", this.render);
this.render();
},
el: $('#content'),
template: Handlebars.compile($("#contentTemplate").html()),
render: function(){
$(this.el).html( this.template(this.model.toJSON()));
},
tagName: "li"
});
var router = Backbone.Router.extend({
initialize: function(){
var newCollection = new collection;
newCollection.fetch();
},
route: {
"": "home"
},
home: function(){
this.view = new view({collection: newCollection});
$('#content').html(this.view.el);
}
});
var app = new router();
}(jQuery))
Thanx.
You are misusing the el attribute. $('#content').html(this.view.el) will result in copying the $('#content') element inside itself (because view.el is equal to $('#content')).
You should try removing the el attribute from the view object and let it generate itself. Then $('#content').html(this.view.el); should work.
One other possible problem is that you are rendering the entire collection inside a li element - was this what you are going for? The best way to go about this would be to have each model in the collection represent a li tag and the collection a ul tag.
Other issues:
the view element is receiving a collection but you are trying to render a model
in the router, newCollection is not accessible in the home method
You are not calling Backbone.history.start()
Here is how i would rewrite the code:
var model = Backbone.Model.extend({
idAttribute: 'custId'
});
var model_view = Backbone.View.extend({
template: Handlebars.compile($("#modelTemplate").html()),
tagName: 'li',
initialize: function() {
_.bindAll(this, 'render');
this.render();
this.on('change',this.render);
},
render: function() {
$(this.el).html( this.template(this.model.toJSON()) );
return this;
}
});
var collection = Backbone.Collection.extend({
initialize: function(){
},
model: model,
url: '/cust'
});
var collection_view = Backbone.View.extend({
tagName: "ul",
initialize: function(){
_.bindAll(this, 'render','renderModels');
this.render();
this.renderModels();
this.collection.bind("reset", this.render);
this.collection.bind("reset", this.renderModels);
},
render: function(){
// just create the 'ul' tag; we will populate it with model view elements; a collection template is no longer needed
return this;
},
renderModels: function() {
this.collection.each(function(obj){
var view = new model_view({
model: obj
});
$(this.el).append(view.el);
},this);
}
});
var router = Backbone.Router.extend({
initialize: function(){
this.newCollection = new collection();
this.newCollection.fetch();
},
route: {
"": "home"
},
home: function(){
this.view = new collection_view({collection: this.newCollection});
$('#content').html(this.view.el); // #content should not be a 'ul' tag, the 'ul' is generated by the collection_view
}
});
var app = new router();
Backbone.history.start();
Make sure you update your templates accordingly.
Please excuse possible errors, i had no means to test the code but i believe it points out the logic you should use.
Cheers!

Backbone.js not rendering

My collection is not rendering for some reason. Cannot find out why.
TreeItem = Backbone.Model.extend({
});
TreeList = Backbone.Collection.extend({
model: TreeItem,
url: "/get_tree_list"
});
window.tree_list = new TreeList();
// VIEW
window.TreeItemView = Backbone.View.extend({
tagName: 'li',
initialize: function(){
_.bindAll(this, 'render');
},
render: function(){
$(this.el).html('<span>'+this.model.get('title')+'</span>');
return this;
}
});
window.TreeListView = Backbone.View.extend({
el: "#tree-structure",
events: {
},
initialize: function() {
_.bindAll(this, 'appendItem', 'render');
tree_list.bind('add', this.appendItem);
tree_list.fetch();
this.render();
},
render: function() {
tree_list.each(this.appendItem);
return this;
},
appendItem: function(item){
var tree_item_view = new TreeItemView({
model: item
});
$(this.el).append(tree_item_view.render().el);
}
});
var tree_list_view = new TreeListView;
Backbone.js provides a lot to be interpreted that's where people new go wrong. Your mistake is fundamental in nature. You tie the View directly to the model
see initialize function where a instance of collection is rendered!!
Always and anywhere you create model, collection pass then as parameters to the constructor of views. Check my fiddle
Never call render inside model, view or collection. They must be inside application file
JsFiddle
http://jsfiddle.net/35QGM/

Resources