View doesn't shows backbone models in template - backbone.js

i'm starting with Backbone and Laravel, and i have severals questions because i don`t find anything in Spanish (maybe i don't know how to search, therefore it's easier to ask).
Here are my Models:
window.mMateria = Backbone.Model.extend({
defaults: {
nombremateria: ""
},
});
window.cMaterias = Backbone.Collection.extend({
url: "materias",
model: mMateria,
initialize: function() {
this.fetch();
}
});
Here are my Views:
window.vMaterias = Backbone.View.extend({
tagName: 'ul',
model: cMaterias,
className:'list-materias',
initialize: function () {
_.bindAll(this, "render");
},
render: function(){
$(this.el).append("Renderizando!"); //It appears
_.each(this.model.models, function (aMater) {
console.log(aMater); //HERE IT DOESN'T ENTER, doesn't show anything
$(this.el).append(new vMateria({model:aMater}).render().el);
}, this);
return this;
},
el: $(".container-fluid")
});
window.vMateria = Backbone.View.extend({
initialize:function () {
_.bindAll(this, "render");
this.model.bind("change", this.render(), this);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
className: "item-materia",
el: $(".container-fluid"),
template: _.template($('#pl_materia').val()),
});
Then initialize:
cmaterias = new cMaterias();
console.log(cmaterias); //it returns 41 signatures
vmaterias = new vMaterias({model: cmaterias});
console.log(vmaterias); //Shows child {cid: "view1", model: child, ...
vmaterias.render().el;
Please help me and excuse my English, I dont know if Laravel with the
return Response::eloquent(Materia::all()); is the problem. Be as especific as possible. Dios los bendiga.

Try these changes.
window.vMaterias = Backbone.View.extend({
tagName: 'ul',
className:'list-materias',
render: function(){
this.$el.empty();
this.$el.append("Renderizando!"); //It appears
this.collection.each(function (aMater) {
console.log(aMater); //HERE IT DOESN'T ENTER, doesn't show anything
this.$el.append(new vMateria({model:aMater}).render().el);
}, this);
return this;
},
el: $(".container-fluid")
});
cmaterias = new cMaterias();
console.log(cmaterias); //it returns 41 signatures
vmaterias = new vMaterias({collection: cmaterias});

Related

Backbone not initializing view. "undefined is not a function"

I'm having problem in backbone where it's not finding my view. Here's the code
Here's the views.
App.Views.SummaryTableView = Backbone.View.extend({
tagName: 'tbody',
initialize: function () {
this.childViews = [];
this.collection.on('add', this.addOne, this);
this.collection.on('change reset', this.render, this);
console.log(this.collection);
},
addOne: function (appSummary) {
console.log('should be receiving model');
console.log(appSummary);
var appSumTable = new App.Views.SummaryListView({ model: appSummary });
console.log(appSummary);
this.$el.append(appSumTable.render().el);
this.childViews.push(appSumTable);
},
render: function () {
console.log('rendiring collection: ' + this.collection);
this.collection.each(this.addOne, this);
console.log('sending the model');
return this;
},
close: function () {
this.remove();
this.unbind();
this.childViews = [];
}
});
App.Views.SummaryListView = Backbone.View.extend({
tagName: 'tr',
template: template('app-summary-table-template'),
initialize: function () {
console.log(this.model);
this.model.on('add', this.render, this);
},
render: function () {
console.log('rendering');
var mod = this.model.toJSON();
this.$el.html(this.template(mod));
return this;
},
close: function () {
this.remove();
this.unbind();
}
});
The SummaryTableView has the collection, and the view sends the model to the SummaryListView. The collection is working fine, and the model contains the data. But for some reasons, when I run the code, it keeps saying SummaryListView is undefined. It can't find the view. Am I doing something wrong? I get the error in this line :
var appSumTable = new App.Views.SummaryListView({ model: appSummary });
you are referring SummaryListView before it is declared , hence the error So
you must Declare SummaryListView before SummaryTableView
the order should be like this
App.Views.SummaryListView = Backbone.View.extend({
tagName: 'tr',
.
.
});
App.Views.SummaryTableView = Backbone.View.extend({
tagName: 'tbody',
.
.
addOne: function (appSummary) {
console.log('should be receiving model');
console.log(appSummary);
var appSumTable = new App.Views.SummaryListView({ model: appSummary});
.
.
});
Fiddle

Backbone.js auto render view after destroy

I have the 2 views for my model. One creates the ul view, the other add the li elements. The views work but they do not update after the destroy function is called. I've tried various ways to bind to the render function, but it is not being called after this.model.destroy(); What am I missing?
var NoteListView = Backbone.View.extend({
tagName:'ul',
className: 'note-group',
initialize:function () {
_.bindAll(this, "render"); // I've tried all these:
this.model.bind("change", this.render, this);
this.model.bind("destroy", this.render, this);
this.model.bind("reset", this.render, this);
this.model.bind('change', _.bind(this.render, this));
this.model.on('change',this.render,this);
},
render:function (eventName) {
_.each(this.model.models, function (note) {
$(this.el).append(new NoteListItemView({
model:note
}).render().el);
}, this);
return this;
}
});
var NoteListItemView = Backbone.View.extend({
tagName:"li",
className: 'note-item',
template:_.template($('#tpl-note-item').html()),
initizlize:function(){
this.model.on('change',this.render,this);
},
render:function (eventName) {
$(this.el).html(this.template(this.model.toJSON()));
return this;
},
events: {
"click .note-btn-delete": "deleteNote"
},
deleteNote: function(e){
this.model.destroy();
}
});
Edit: here's the Collection:
var NoteCollection = Backbone.Collection.extend({
model:Note,
url:"api.php/notes",
initialize: function (models){
this.filtered = new Backbone.Collection(models);
},
filterByCid: function(id) {
var filtered = _.filter(this.models, function (model) {
if (id==0) return true;
return model.get("contactid") == id;
});
}
});
In the router:
this.noteList = new NoteCollection();
this.noteList.fetch({data:{contactid:id},
success: function (collection){
if (collection.length>0){
$('#note-container').html(new NoteListView({model:collection}).render().el);
}
else {
$('#note-container').html('No notes');
}
}
})
I see 2 issues with enter code here your code.
First
You are not listening to the remove event on the NodeListItemView
Second
_.each(this.model.models,
supposed to be
_.each(this.collection.models,
If models is present on the model, then it is supposed to be in the options of the model
_.each(this.model.options.models,
Code
var NoteListView = Backbone.View.extend({
tagName: 'ul',
className: 'note-group',
initialize: function () {
this.listenTo.on(this.collection, 'reset', this.render);
},
render: function (eventName) {
_.each(this.collection.models, function (note) {
$(this.el).append(new NoteListItemView({
model: note
}).render().el);
}, this);
return this;
}
});
var NoteListItemView = Backbone.View.extend({
tagName: "li",
className: 'note-item',
template: _.template($('#tpl-note-item').html()),
initizlize: function () {
_.bindAll(this, "deleteNote", "removeView");
this.listenTo.on(this.model, 'change', this.render);
this.listenTo.on(this.model, 'remove', this.removeView);
},
render: function (eventName) {
$(this.el).html(this.template(this.model.toJSON()));
return this;
},
events: {
"click .note-btn-delete": "deleteNote"
},
deleteNote: function (e) {
this.model.destroy();
},
removeView : function() {
this.remove();
}
});
EDIT
Change this line
new NoteListView({model:collection}).render().el
to use collection instead
new NoteListView({collection :collection}).render().el
And I do not believe your fetch method takes in any data
this.noteList.fetch({data:{contactid:id})
this.noteList.fetch()
It only takes in success and error callbacks

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

Backbone view doesn't render template passed to it

I need to be able to pass different template IDs to different routes.
(function() {
window.App = {
Models: {},
Collections: {},
Views: {},
Router: {}
};
var vent = _.extend({}, Backbone.Events);
_.templateSettings.interpolate = /\[\[(.+?)\]\]/g;
App.Router = Backbone.Router.extend({
routes: {
'' : 'index',
'send-message' : 'sendMessage',
'*other' : 'other'
},
index: function() {
t = new (App.Collections.Tables.extend({ url: 'main-contact'}))();
tables = App.Views.Tables({ collection: t, template: 'mainContactTemplate' });
$('#web-leads').html(tables.el);
},
sendMessage: function() {
// t = new (App.Collections.Tables.extend({ url: 'send-message'}))();
// tables = new App.Views.Tables.extend({ collection: t, template: template('sendMessageTemplate')});
// $('#web-leads').html(tables.el);
},
other: function() {
}
});
// Main Contact
App.Models.Table = Backbone.Model.extend({});
App.Collections.Tables = Backbone.Collection.extend({
model: App.Models.Table,
initialize: function(models, options) {
this.fetch({
success: function(data) {
//console.log(data.models);
}
});
if (options) {
this.url = this.url || options.url;
}
}
});
App.Views.Tables = Backbone.View.extend({
tagName: 'ul',
initialize: function() {
this.collection.on('reset', this.render, this);
},
render: function() {
return this.collection.each(this.addOne, this);
},
addOne: function(model) {
var t = new App.Views.Table({ model: model});
this.$el.append(t.render().el);
return this;
}
});
App.Views.Table = Backbone.View.extend({
tagName: 'li',
initialize: function(options) {
this.template = options.template;
console.log(this.options);
},
retrieveTemplate: function(model) {
return _.template($('#' + this.template).html(), model);
},
render: function() {
this.$el.html(this.retrieveTemplate(this.model.toJSON()));
return this;
}
});
new App.Router();
Backbone.history.start();
})();
But I get an error than n is undefined. I think I need to pass this.template into my retrieveTemplate function. But shouldn't it already be set? This code works, by the way, if I hard code in the name of the template ID in the retrieveTemplate function.
EDIT: the template isn't being passed from the call in the router. That's where this is breaking down.
EDIT: I took out the call to extend in the second line of the index route and now I get this._configure is not a function
WORKING VERSION:
(function() {
window.App = {
Models: {},
Collections: {},
Views: {},
Router: {}
};
var vent = _.extend({}, Backbone.Events);
_.templateSettings.interpolate = /\[\[(.+?)\]\]/g;
App.Router = Backbone.Router.extend({
routes: {
'' : 'index',
'send-message' : 'sendMessage',
'*other' : 'other'
},
index: function() {
var t = new (App.Collections.Tables.extend({ url: 'main-contact'}))();
var tables = new (App.Views.Tables.extend({ collection: t, options: {template: 'mainContactTemplate' }}))();
$('#web-leads').html(tables.render().el);
},
sendMessage: function() {
// t = new (App.Collections.Tables.extend({ url: 'send-message'}))();
// tables = new App.Views.Tables.extend({ collection: t, template: template('sendMessageTemplate')});
// $('#web-leads').html(tables.el);
},
other: function() {
}
});
// Main Contact
App.Models.Table = Backbone.Model.extend({});
App.Collections.Tables = Backbone.Collection.extend({
model: App.Models.Table,
initialize: function(models, options) {
this.fetch({
success: function(data) {
//console.log(data.models);
}
});
if (options) {
this.url = this.url || options.url;
}
}
});
App.Views.Tables = Backbone.View.extend({
tagName: 'ul',
initialize: function(options) {
this.collection.on('reset', this.render, this);
this.template = this.options.template;
},
render: function() {
this.collection.each(this.addOne, this);
return this;
},
addOne: function(model, options) {
//console.log(model);
var t = new App.Views.Table({ model: model, template: this.options.template});
this.$el.append(t.render().el);
return this;
}
});
App.Views.Table = Backbone.View.extend({
tagName: 'li',
initialize: function(options) {
//console.log(this.options);
this.template = this.options.template;
},
retrieveTemplate: function(model) {
return _.template($('#' + this.template).html(), model);
},
render: function() {
//console.log(this);
this.$el.html(this.retrieveTemplate(this.model.toJSON()));
return this;
}
});
new App.Router();
Backbone.history.start();
})();
Your router says this:
tables = App.Views.Tables({ collection: t, template: 'mainContactTemplate' });
So you're giving a template: '...' to App.Views.Tables. The initialize in App.Views.Tables looks like this:
initialize: function() {
this.collection.on('reset', this.render, this);
}
so it ignores the template option. If we look at App.Views.Table (singular!), we see this:
initialize: function(options) {
this.template = options.template;
console.log(this.options);
}
but App.Views.Table is instantiated without a template option:
var t = new App.Views.Table({ model: model});
You need to fix how you use App.Views.Table. Backbone will put a view's constructor options in this.options for you so you just need to say:
var t = new App.Views.Table({ model: model, template: this.options.template });
A couple other things to consider:
You have some accidental globals in your router's index method, you should have var t and var tables rather than just t and tables.
A view's render method conventionally returns this so that you can say $x.append(v.render().el) so you might want to adjust your render methods to match the convention.
You probably need to bind the context. Underscore can help you with that.
.bindAll or .bind should do it.
I typically just use _.bindAll during initialization as shown below.
...
initialize: function(options) {
_.bindAll(this); // apply appropriate context
this.template = options.template;
},
...
Hope this helped, best of luck.

Accessing Properties of Parent Backbone View

I have a backbone view that calls to a sub-view:
lr.MapView = Backbone.View.extend({
el: $('#map'),
foo: "bar",
initialize: function() {
var that = this;
_.bindAll(this, "render", "addAllEvents", "addOneEvent");
this.collection = new lr.Events();
this.collection.fetch({
success: function(resp) {
that.render();
that.addAllEvents();
}
});
},
addAllEvents: function() {
this.collection.each(this.addOneEvent);
},
addOneEvent: function(e) {
var ev = new lr.EventView({
model: e
});
},
render: function() {
}
});
Here is the sub-view:
lr.EventView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, "render");
console.log(lr.MapView.foo); // will console.log 'undefined'
},
render: function() {
}
});
I'd like to be able to access properties the parent view within the sub-view, but it isn't working with the above code. For example, how can I access the 'foo' variable within the sub-view?
lr.MapView is a "class", everything that Backbone.View.extend builds will be in lr.MapView.prototype, not in lr.MapView. Run this with the console open and you'll see whats going on:
var MapView = Backbone.View.extend({ foo: 'bar' });
console.log(MapView);
console.log(MapView.prototype);
console.log(MapView.prototype.foo);
Demo: http://jsfiddle.net/ambiguous/DnvR5/
If you're only going to have a single MapView then you can refer to lr.MapView.prototype.foo everywhere:
initialize: function() {
_.bindAll(this, "render");
console.log(lr.MapView.prototype.foo);
}
Note that everywhere includes within lr.MapView instances so your foo will act like a "class variable" from non-prototype based OO languages.
The right way to do this is to use an instance variable for foo and pass the parent view instance to the sub-view instances when they're created:
// In MapView
addOneEvent: function(e) {
var ev = new lr.EventView({
model: e,
parent: this
});
}
// In EventView
initialize: function(options) {
_.bindAll(this, "render");
this.parent = options.parent; // Or use this.options.parent everywhere.
console.log(this.parent.foo);
}
Or better, add an accessor method to MapView:
_foo: 'bar',
foo: function() { return this._foo }
and use that method in EventView:
initialize: function(options) {
// ...
console.log(this.parent.foo());
}
Proper encapsulation and interfaces are a good idea even in JavaScript.
Just a guess, but could you try something like this in MapView:
addOneEvent: function(e) {
var that = this,
ev = new lr.EventView({
model: e,
parentView = that
});
}
And then access it like this:
lr.EventView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, "render");
console.log(this.parentView.foo);
},
render: function() {
}
});

Resources