Bootstrapping data in backbone.js? - javascript

I've manage to put together the below code through various examples, which seems to work okay, but it doesn't seem to preload my data, can anyone please tell me what I'm missing?
App = (function(Backbone, _){
var Note = Backbone.Model.extend(
{
defaults:
{
part1: 'hello',
part2: 'world'
}
});
var TableList = Backbone.Collection.extend({
model: Note
});
var ListRow = Backbone.View.extend(
{
tagName: 'li',
initialize: function()
{
_.bindAll(this, 'render');
},
render: function()
{
$(this.el).html('<span>'+this.model.get('part1')+' '+this.model.get('part2')+'</span>');
return this;
}
});
var ListView = Backbone.View.extend(
{
el: $('#layout_content'),
events:
{
'click button#add': 'addItem'
},
initialize: function()
{
_.bindAll(this, 'render', 'addItem', 'appendItem');
this.collection = new TableList();
this.collection.bind('add', this.appendItem);
this.counter = 0;
this.render();
},
render: function()
{
var self = this;
$(this.el).append("<button id='add'>Add list item</button>");
$(this.el).append("<ul></ul>");
_(this.collection.models).each(function(item){ // in case collection is not empty
self.appendItem(item);
}, this);
},
addItem: function()
{
this.counter++;
var note = new Note();
note.set({part2: note.get('part2') + this.counter});
this.collection.add(note);
},
appendItem: function(item)
{
var listRow = new ListRow({
model: item
});
$('ul', this.el).append(listRow.render().el);
}
});
var app = function(initialModels)
{
this.start = function()
{
this.tableList = new TableList();
this.listView = new ListView({collection: this.tableList});
this.tableList.reset(initialModels);
};
};
return app;
})(Backbone, _);
then init the app with:
<script language="javascript">
var app = new App([{"id":"95","note_title":"can we find the title"},{"id":"93","note_title":"some title"}]);
app.start();
</script>

okay, there are a few issues with your code,
there are 2 issues in your start method,
a) you throw away your collection
this.start = function()
{
this.tableList = new TableList();
this.listView = new ListView({collection: this.tableList});
this.tableList.reset(initialModels);
};
and then in intialize is where you overwrite the collection you pass along
initialize: function()
{
_.bindAll(this, 'render', 'addItem', 'appendItem');
this.collection = new TableList(); // this one gets overwritten, remove this line
}
b) you trigger a collection reset with the models you want to populate it with, but don't listen to an event, either add a listener like this:
this.collection.bind('reset', this.appendAllItems, this);
or create your collection like this:
this.start = function()
{
this.tableList = new TableList(initialModels);
this.listView = new ListView({collection: this.tableList});
};

Related

Cannot retrieve collection outside of the view

I'm making a simple list of people with option when clicking on person's name the Router will take a name as a parameter 'student/:name' and find a right person's object in a collection. I instantiate collection in a GroupView class by fetching it from the server. And that's where the Error appears: to get the access to collection (so I can find right object) in my viewStudent() method in Router class, I'm making one more instance of GroupView(), and console shows an error and that's right, 'cause there're no objects in collection.
I cannot wrap my head around this, why in GroupView() I receive data from the server and my collection just works fine, but second time I instantiate GroupView() in a Router - there's no collection? Maybe there's any other way I can get access to the collection in my Router? Any help would be greatly appreciated.
var StudentModel = Backbone.Model.extend({
defaults: {
name: 'Volodya',
lastName: 'Peterson',
age: 22,
gender: 'male'
}
});
var StudentsCollection = Backbone.Collection.extend({
model: StudentModel,
url: '/students.json'
});
var StudentView = Backbone.View.extend({
tagName: 'li',
template: _.template($('#studentTpl').html()),
events: {
'click': function () {
eventAggregator.trigger('student:selected', this.model);
}
},
render: function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var GroupView = Backbone.View.extend({
tagName: 'ul',
initialize: function () {
this.collection = new StudentsCollection();
this.collection.on('update', this.render, this);
this.collection.fetch();
},
render: function () {
var self = this;
this.collection.each(function (student) {
var studentView = new StudentView({
model: student
});
self.$el.append(studentView.render().el);
});
$('body').html(this.$el);
}
});
var RouterView = Backbone.View.extend({
tagName: 'ul',
render: function () {
var self = this;
_.each(this.model.toJSON(), function (value) {
self.$el.append('<li>' + value + '</li>');
});
return this;
}
});
var GroupController = function () {
this.start = function () {
var groupView = new GroupView();
};
};
var Router = Backbone.Router.extend({
routes: {
'': 'index',
'student/:name': 'viewStudent'
},
index: function () {
groupController.start();
},
viewStudent: function (name) {
var groupView = new GroupView();
var selectedStudent = groupView.collection.find(function (student) {
return student.get('name') === name;
});
$('body').append((new RouterView({ model : selectedStudent})).render().el);
}
});
var eventAggregator= _.extend({}, Backbone.Events),
groupController;
$(function () {
var router = new Router();
groupController = new GroupController();
Backbone.history.start();
eventAggregator.on('student:selected', function (student) {
var urlpath= 'student/'+ student.get('name');
router.navigate(urlpath, {trigger: true});
});
});

Render each row with template - Backbone

Heres my code:
var RowsSubView = Backbone.View.extend({
initialize: function() {
log.debug(this.collection);
},
render: function() {
var html = RowView();
this.setElement(html);
return this;
}
});
var View = BaseView.extend({
id: 'wrapper',
className: 'container-fluid',
events: {
},
initialize: function() {
_.bindAll(this, 'render');
log.debug('Initialized Queue View');
this.opportunities = new Opportunities();
this.opportunities.on('add', function(model){
});
this.opportunities.fetch({
success: function(response, options) {
},
error: function(response) {
}
});
},
render: function() {
var template = QueueView();
this.$el.html(template);
this.renderRowsSubView();
return this;
},
renderRowsSubView: function() {
// render rows
this.row = new RowsSubView({collection: this.opportunities});
this.row.render();
this.$el.find('tbody').append(this.row.el);
}
});
Heres my question:
Sorry for the noob question! I am learning Backbone and having a bit of an issue. I've looked at a bunch of tutorials/guides, but I think I've confused myself.
I am trying to create a list of items and render them in a table. I want to pass each item into my template and spit it out in the view.
I am stuck after passing my collection to my RowsSubView. I'm not sure how to render each object in the template. Then insert those.
PS: I am able to log this.collection in my RowsSubView and see an object with the array of items.
Thanks.
Ok well start with this. Looks like there's quite a bit of cleanup that needs to be done =)
var RowsSubView = Backbone.View.extend({
initialize: function() {
log.debug(this.collection);
},
render: function() {
//var html = RowView(); // Looks like you're already placing a tbody as the container
//this.setElement(html);
this.collection.forEach(function( model ){
this.$el.append( RowView( model.toJSON() ) ); // Assuming RowView knows what to do with the model data
});
return this;
}
});
Then change the renderRowsSubView to
renderRowsSubView: function() {
// render rows
this.row = new RowsSubView({collection: this.opportunities});
this.row.render();
this.$el.find('tbody').append(this.row.$el.html());
}
For those that this might help, heres what I ended up with:
var RowsSubView = Backbone.View.extend({
initialize: function() {
},
render: function() {
var html = RowView({
opp: this.model.toJSON()
});
this.setElement(html);
return this;
}
});
var View = BaseView.extend({
id: 'wrapper',
className: 'container-fluid',
events: {
},
initialize: function() {
_.bindAll(this, 'render', 'add');
log.debug('Initialized Queue View');
this.opportunities = new Opportunities();
this.opportunities.on('add', this.add);
this.fetch();
},
add: function(row) {
this.row = new RowsSubView({model: row});
this.row.render();
$('tbody').append(this.row.el);
},
fetch: function() {
this.opportunities.fetch({
data: $.param({
$expand: "Company"
}),
success: function(response, options) {
// hide spinner
},
error: function(response) {
// hide spinner
// show error
}
});
},
render: function() {
var template = QueueView();
this.$el.html(template);
return this;
}
});
return View;
});

this.collection.each doesn't iterate

I am trying to understand Backbone and tried to create some small REST API fronted, but can not get View to work.
fetch() returns valid JSON array of three elements. And this.collection.models is not empty (typeof object - []) - it has tree child object elements in it. But each iteration doesn't fire.
When check if collection.models exists with console.log(this.collection.models); it looks like all is right:
I would be thankful for any advice!
var Account = Backbone.Model.extend({});
var AccountsCollection = Backbone.Collection.extend({
model: Account,
url: 'api/v1/accounts',
initialize: function () {
this.fetch();
}
});
var AccountsView = Backbone.View.extend({
render: function() {
// Check if there is something
console.log(this.collection.models);
// This doesn't work
_.each(this.collection.models, function(model) {
console.log(model);
});
// Neither this
this.collection.each(function(model) {
console.log(model);
});
}
});
var a = new AccountsView({collection: new AccountsCollection()});
a.render();
First option
var AccountsCollection = Backbone.Collection.extend({
model: Account,
url: 'api/v1/accounts'
});
var AccountsView = Backbone.View.extend({
render: function() { /**/ }
});
var collection = new AccountsCollection();
var view = new AccountsView({collection:collection});
collection.fetch().done(function () {
// collection has been fetched
view.render();
});
Second option
var AccountsCollection = Backbone.Collection.extend({
model: Account,
url: 'api/v1/accounts'
});
var AccountsView = Backbone.View.extend({
initialize: function() {
this.listenTo(this.collection, 'sync', this.render);
},
render: function() { /**/ }
});
var collection = new AccountsCollection();
var view = new AccountsView({collection:collection});
Third option
var AccountsCollection = Backbone.Collection.extend({
model: Account,
url: 'api/v1/accounts',
initialize: function () {
this.deferred = this.fetch();
}
});
var AccountsView = Backbone.View.extend({
initialize: function() {
this.collection.deferred.done(_.bind(this.render, this));
},
render: function() { /**/ }
});
var collection = new AccountsCollection();
var view = new AccountsView({collection:collection});

Learning Backbone.js - Cannot convert 'this.model' to object

i'm newbie, trying to learn Backbone.js, and i've got this error:
Cannot convert 'this.model' to object
I'm trying to build an easy architecture for audioplayer, but this error makes me mad! Don't understand why it happens, but browser console shows error in line this.model.bind("reset", this.render, this) of ListOfSongsView.
Here's my code:
$(function () {
var Player = Backbone.Model.extend({
defaults:{
//blablabla
}
});
var Playlist = Backbone.Collection.extend({
model: Player
});
var MyPlaylist = new Playlist([
{
//blablabla
}
//here comes more songs
]);
var ListOfSongsView = Backbone.View.extend({
tagName: 'ul',
id: "tracks",
initialize: function () {
this.model.bind("reset", this.render, this);
var self = this;
this.model.bind("add", function (player) {
$(self.el).append(new OneSongView({model:player}).render().el);
});
},
render: function (eventName) {
_.each(this.model.models, function (player) {
$(this.el).append(new OneSongView({model:player}).render().el);
}, this);
return this;
}
});
var OneSongView = Backbone.View.extend({
tagName: "li",
calssName: "clearfix",
template:_.template($('#tpl-one-song').html()),
initialize: function () {
this.model.bind("change", this.render, this);
},
render: function (eventName) {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
var AppRouter = Backbone.Router.extend({
routes:{
"": "list",
"!/": "list"
},
initialize: function () {
$('#block').html(new ListOfSongsView().render().el);
},
list: function () {
this.playlist = new Playlist();
this.ListOfSongsView = new ListOfSongsView({model:this.playlist});
this.playlist = MyPlaylist;
$('#block').html(new ListOfSongsView().render().el);
}
});
var app = new AppRouter();
Backbone.history.start();
});
What i'm doing wrong?
Please, help me, my head is already cracked :(
initialize: function () {
$('#block').html(new ListOfSongsView().render().el);
}
This is called the moment you construct the AppRouter.
You pass no model in argument of ListOfSongsView(), so this.model is undefined.
Then the initialize of the view is called:
initialize: function () {
this.model.bind("reset", this.render, this);
var self = this;
this.model.bind("add", function (player) {
$(self.el).append(new OneSongView({model:player}).render().el);
});
},
this.model is undefined, so you can't call bind on it.

Backbone.js render().el Usage

I've got this piece of code from a Backbone.js tutorial from here. The code is as follows:
(function($){
var Item = Backbone.Model.extend({
defaults: {
part1: 'Hello',
part2: 'World'
}
});
var ItemList = Backbone.Collection.extend({
model: Item
});
var ItemView = Backbone.View.extend({
tagName: 'li',
initialize: function(){
_.bindAll(this, 'render');
},
render: function(){
$(this.el).html("<span>" + this.model.get('part1') + " " + this.model.get('part2') + "</span>");
return this;
}
});
var AppView = Backbone.View.extend({
el: $('body'),
initialize: function(){
_.bindAll(this, 'render', 'addItem', 'appendItem');
this.collection = new ItemList();
this.collection.bind('add', this.appendItem)
this.counter = 0;
this.render();
},
events: {
'click button#add': 'addItem'
},
addItem: function(){
var item = new Item();
item.set({
'part2': item.get('part2') + this.counter++
});
this.collection.add(item);
},
appendItem: function(item){
var itemView = new ItemView({
model: item
});
$('#list', this.el).append(itemView.render().el);
},
render: function(){
$(this.el).append("<button id='add'>Add Item</button>");
$(this.el).append("<ul id='list'></ul>")
},
});
var Tasker = new AppView();
})(jQuery);
There is one thing I could not understand from the above code. In the function appendItem there is this piece of code:
itemView.render().el
Could anybody explain me why the render() function is called with the .el part and why not just itemView.render()?
Thank you for your time and help :-)
The render() call returns the itemView itself. It then asks for the el instance variable (the element itself), which is then appended to the list view. In essence, the list view includes all the elements of the items rendered individually.

Categories