I have a rather simple backbone view that renders a tag when iterating through each item in a collection via the _.each function.
var SingleView = Backbone.View.extend({
tagName:td,
//other stuff
});
I have a view for the collection as well
var CollectionView = Backbone.View.extend({
//other stuff
this.collection.each(function(model ,i) {
var item = new SingleView({model: model});
//alert(i);
//maybe in here is where I need logic to wrap a row around a <td> tag ?
$('.collection').append(item.render().$el);
});
Then in the template:
<table class = "collection">
<!-- variables to render as html -->
</table>
What I'm hoping to do is wrap a given number of items in a table row, or <tr></tr>. It's easy to get one cell/row. I'm trying to get 2 or 3 or however many cells per row that I want. I've tried the Jquery wrap feature, and I'm guessing I need some kind of modular division but I'm kind of stuck. I'm also new to Backbone which is another hurdle.
To clarify - an individual item in the collection should be in each <td>, and I'm trying to place > 1 <td> in each row.
I tried to create a working example as close to your explanation as possible. It renders a collection as table cells, and I think you can go from there.
Basically, you shouldn't manually wrap your td's in a tr tag. Create instances of TrView and TdView respectively, depending on the flow of your data. Append tr to table, and td to tr.
Also you might want to look at CollectionView implemented in Marionette:
http://marionettejs.com/docs/v2.4.3/marionette.collectionview.html
Example #1:
var collection = new Backbone.Collection([
{ title: 'Item 1' },
{ title: 'Item 2' },
{ title: 'Item 3' }
]);
var TableView = Backbone.View.extend({
tagName: "table",
className: "collection",
render: function(){
var rowView = new RowView({ collection: collection });
this.$el.html( rowView.render().el );
return this;
}
});
var RowView = Backbone.View.extend({
tagName: "tr",
render: function(){
this.collection.each(this.appendItem, this);
return this;
},
appendItem: function(model){
var tdView = new TdView({ model:model });
this.$el.append( tdView.render().el );
}
});
var TdView = Backbone.View.extend({
tagName: "td",
render: function(){
this.$el.text( this.model.get('title') );
return this;
}
});
var tableView = new TableView();
tableView.render().$el.appendTo(document.body);
table {
border: 1px solid steelblue;
}
td {
border: 1px solid brown;
padding: 3px 5px;
}
<script src='http://code.jquery.com/jquery.js'></script>
<script src='http://underscorejs.org/underscore.js'></script>
<script src='http://backbonejs.org/backbone.js'></script>
Example #2:
var collection = new Backbone.Collection([
{ title: 'Item 1' },
{ title: 'Item 2' },
{ title: 'Item 3' },
{ title: 'Item 4' },
{ title: 'Item 5' },
{ title: 'Item 6' }
]);
var TableView = Backbone.View.extend({
tagName: "table",
className: "collection",
initialize: function(o){
this.maxItemsInRow = o.maxItemsInRow? o.maxItemsInRow: 3;
},
render: function(){
this.collection.each(this.addItem, this);
return this;
},
addRow: function(){
var rowView = new RowView({ collection: collection });
rowView.$el.appendTo( this.el );
this.currentRow = rowView;
this.currentRowItemsLength = 0;
},
addItem: function(model){
if( typeof this.currentRow === 'undefined') {
this.addRow();
}
this.currentRow.addItem(model);
this.currentRowItemsLength++;
if(this.currentRowItemsLength >= this.maxItemsInRow){
this.currentRow = undefined;
}
}
});
var RowView = Backbone.View.extend({
tagName: "tr",
addItem: function(model){
var tdView = new TdView({ model:model });
this.$el.append( tdView.render().el );
}
});
var TdView = Backbone.View.extend({
tagName: "td",
render: function(){
this.$el.text( this.model.get('title') );
return this;
}
});
var tableView = new TableView({ collection: collection, maxItemsInRow: 3 });
tableView.render().$el.appendTo(document.body);
table {
border: 1px solid steelblue;
}
td {
border: 1px solid brown;
padding: 3px 5px;
}
<script src='http://code.jquery.com/jquery.js'></script>
<script src='http://underscorejs.org/underscore.js'></script>
<script src='http://backbonejs.org/backbone.js'></script>
Something like this?
http://jsfiddle.net/9mjcmgpo/
var SingleView = Backbone.View.extend({
tagName: 'tr',
template: _.template('<td><%=name%></td><td><%=age%></td><td><%=sex%></td>'),
render: function() {
this.$el.append(this.template(this.model.toJSON()))
return this
}
});
var CollectionView = Backbone.View.extend({
template: _.template('<tr><th>name</th><th>age</th><th>sex</th></tr>'),
initialize: function() {
this.$el = $('.collection');
this.el = this.$el[0];
// sudo collection
this.collection = new Backbone.Collection();
this.collection.add({'name': 'test1', 'sex': 'f', age: 21});
this.collection.add({'name': 'test2', 'sex': 'o', age: 25});
this.collection.add({'name': 'test3', 'sex': 'm', age: 26});
// hack
this.render();
},
render: function() {
this.$el.html(this.template());
this.collection.each(_.bind(function(model) {
var item = new SingleView({model: model});
this.$el.append(item.render().$el);
}, this));
return this;
}
});
new CollectionView()
You can do something like the following. I have hard coded 3 as the number of rows. You can use variable number by passing it to the view if necessary.
var collection = new Backbone.Collection([{
title: 'Item 1'
}, {
title: 'Item 2'
}, {
title: 'Item 3'
}, {
title: 'Item 4'
}, {
title: 'Item 5'
}]);
var TdView = Backbone.View.extend({
tagName: "td",
initialize: function() {
this.render();
},
render: function() {
this.$el.text(this.model.get('title'));
return this;
}
});
var TableView = Backbone.View.extend({
tagName: "table",
className: "collection",
initialize: function() {
this.render();
},
render: function() {
var $tr = $('<tr/>');
var count = 1;
this.collection.each(function(model, i) {
if ((i / 3) >= count) { // end of current row
this.$el.append($tr); //append current row
$tr = $('<tr/>'); // create new row
count = this.$el.find('tr').length + 1; // refresh counter
}
$tr.append(new TdView({ // append td to current row
model: model
}).el);
}, this);
this.$el.append($tr); // append final row
return this;
}
});
var tableView = new TableView({
collection: collection
});
tableView.$el.appendTo('body');
table {
border: 1px solid steelblue;
}
td {
border: 1px solid brown;
padding: 3px 5px;
}
<script src='http://code.jquery.com/jquery.js'></script>
<script src='http://underscorejs.org/underscore.js'></script>
<script src='http://backbonejs.org/backbone.js'></script>
Related
I'm facing a very weird problem using ListenTo on subviews.
Basically I've a main view that contains multiple subviews.
Those subviews are initialized when their parent view is also initialized.
Some of those subviews are listening to the same global collection.
One of those views is a form that allow me to insert new entries into the collection
The second one is a list of all those entries contained into the collection.
So, basically it looks like this
$('button').on('click'....
app.views.MyMainView = new MyMainView()
//launch new modal window
//with html body = app.views.MyMainView.el
var MyMainView = Backbone.view.extend({
initialize: function(){
// new Form_View()
// new List_View()
}
});
var Form_View = Backbone.view.extend({
//get input value
// create new entrie into the collection
});
var List_View = Backbone.view.extend({
initialize: function(){
// listenTo(this.collection, 'add', this.addOne)
// new List_View()
this.addAll();
},
addAll: function(){...},
addOne: function(model){ .... }
});
The problem is the following:
When the user launch the modal for the first time and we add a new entry to the collection
the listenTo add on the List_View fires as expected.
If I close the modal and the user clicks on 'button' to launch the modal window once again if I add a new entrie the view will fire 2 times the function that is listening to the collection add event.
If i close the modal again and re-open it the function will fire 3 times and so on.
This is weird because I'm creating a new instance of the view and their subviews everytime the user clicks on the 'button'. That's why it doesn't make sense to me.
Any help?
EDIT
I also checked my collection by listening to the 'add' event inside of it.
var MyCollection = Backbone.View.extend({
initialize: function(){
this.listenTo( this, 'add', doSomething );
},
doSomething: function( model ){
//do something fires as it should be firing the event: 1 time per each item inserted
}
})
EDIT 2
var MyMainView = Backbone.View.extend({
.....
close_modal: function(e){
if(e){
e.preventDefault();
}
var viewsLen = this.views.length,
_that = this;
_.each(this.views, function(view, key){
view.remove();
if(key + 1 == viewsLen )
_that.dialog.close();
})
}
...
})
EDIT 3:
ALL CODE
//initialize modal
$('button').on('click', function(){
app.views.storePayment_View = new StorePayment_View();
})
var TMPL_StorePayment = '<div class="store-payment">'
+ '<div class="store-payment-header">'
+ '<div class="client"></div>'
+ '<div class="status"></div>'
+ '</div>'
+ '<div class="payment-form"></div>'
+ '<div class="payment-list"></div>'
+ '<div class="x-form-actions">'
+ '</div>'
+ '</div>';
var StorePayment_View = Backbone.View.extend({
views: {},
wrappers: {},
collections: {},
events: {
"click .back": "close_modal",
"click .finish-payment": "finish_payment"
},
initialize: function(){
var _that = this;
this.dialog = new BootstrapDialog({
title: appLang["h67"],
message: this.$el,
closable: true,
onhide: function(dialogRef){
_that.remove();
}
});
this.dialog.realize();
this.dialog.getModalFooter().hide();
this.dialog.open();
this.$el.html('').append( TMPL_StorePayment );
this.wrappers.$client = this.$el.find('.client');
this.wrappers.$status = this.$el.find('.status');
this.wrappers.$payment_form = this.$el.find('.payment-form');
this.wrappers.$payment_list = this.$el.find('.payment-list');
this.wrappers.$form_actions = this.$el.find('.x-form-actions');
this.render()
},
render: function(){
this.views.StorePaymentForm_View = new StorePaymentForm_View();
this.wrappers.$payment_form.html('').append( this.views.StorePaymentForm_View.el );
this.views.StorePaymentList_View = new StorePaymentList_View();
this.wrappers.$payment_list.html('').append( this.views.StorePaymentList_View.el );
},
close_modal: function(e){
if(e){
e.preventDefault();
}
var viewsLen = this.views.length,
_that = this;
_.each(this.views, function(view, key){
view.remove();
if(key + 1 == viewsLen ){
_that.dialog.close();
}
})
}
})
var StorePaymentForm_View = Backbone.View.extend({
error_tmpl: _.template('<div class="alert alert-warning"><%= message %></div>') ,
template: _.template('<div> <div class="input-field"> <input type="text" class="montant form-control" value="<%= restant %>"> </div> <div class="input-select"> <select name="payment-type"><% _.each(paymentTypeList, function(paymentType){ %> <option value="<%= paymentType.typeMode %>"><%= paymentType.libelle %></option> <% }) %></select> </div> <div class="actions">Add newRemove All </div></div><div class="error_placeholder"></div>'),
events:{
"click .add-new": "add_new",
"click .remove-all": "remove_all"
},
initialize: function(){
this.collection = app.collections.StorePaymentList;
this.listenTo( this.collection, 'add', this.render )
this.listenTo( this.collection, 'destroy', this.render )
this.listenTo( this.collection, 'change', this.render )
this.listenTo( this.collection, 'reset', this.render )
this.render()
},
render: function(){
console.log("RENDER FIRED ON STOREPAYMENTFORM")
var restant = this.collection.getRestant();
if ( restant <= 0){
restant = 0;
}
this.$el.html('').append( this.template( { "restant" : restant, "paymentTypeList": app.collections.PaymentTypeList.toJSON() } ) )
var _that = this;
setTimeout(function(){
_that.$el.find('select').selectBoxIt({
native: true,
autoWidth: false
})
_that.$el.find('input').focus();
}, 50 )
},
add_new: function(e){
console.log("add_new");
if(e){
e.preventDefault();
}
var _that = this,
input_val = this.$el.find('input').val(),
select_val = this.$el.find('select :selected').val(),
libelle = this.$el.find('select :selected').text(),
wasNaN = false;
input_val = parseInt(input_val);
if (isNaN(input_val)){
wasNaN = true;
input_val = 0;
}
if (wasNaN){
_that.$el.find('.error_placeholder').html( _that.error_tmpl( { "message": appLang["h69"] } ) );
} else {
if ( input_val <= 0 ){
_that.$el.find('.error_placeholder').html( _that.error_tmpl( { "message": appLang["h70"] } ) );
} else {
this.collection.add( new StorePaymentModel( { "libelle": libelle , "paymentId": select_val, "montant": input_val } ) )
}
}
},
remove_all: function(e){
if(e){
e.preventDefault();
}
var _that = this;
//dialog are you sure?
var dialog = new BootstrapDialog({
title: "Do you want to continue",
message: "Do you really want to empty your current list of payments?",
buttons: [{
label: appLang["a187"], //cancel
action: function(dialog) {
dialog.close();
}
}, {
label: appLang["a1621"], //ok
cssClass: 'btn-primary',
action: function(dialog) {
_that.collection.reset([]);
dialog.close();
}
}]
})
dialog.realize();
dialog.open();
}
})
var StorePaymentListItem_View = Backbone.View.extend({
events:{
"click .remove": "remove_item",
"click .save": "save"
},
template: _.template( '<%= libelle %> <%= montant %> <i class="fa fa-trash-o"></i>' ),
tagName: 'li',
className: 'list-group-item',
initialize: function(){
this.render()
//console.log("StorePaymentListItem_View initialized")
this.listenTo( this.model, 'hide', this.remove )
},
render: function(){
this.$el.html('').append( this.template( this.model.toJSON() ) )
},
edit: function(){
this.render_edit();
},
save: function(e){
if (e){
e.preventDefault(); e.stopPropagation();
}
this.render();
},
remove_item: function(e){
if (e){
e.preventDefault(); e.stopPropagation();
}
this.model.destroy();
}
})
var StorePaymentList_View = Backbone.View.extend({
$wrapper: $('<ul />', {'class': 'list-group' }),
initialize: function(){
this.$el.html('');
this.collection = app.collections.StorePaymentList;
this.listenTo( this.collection , 'add', this.addOne );
this.listenTo( this.collection , 'change', this.render );
this.listenTo( this.collection , 'reset', this.render );
this.render()
},
render: function(){
var totalItems = this.collection.length;
this.$wrapper.html('')
if (totalItems == 0){
this.appendToRoot();
} else {
this.addAll()
}
},
addAll:function(){
var _that = this,
totalItems = this.collection.length;
this.collection.forEach(function(model, key){
_that.addOne(model)
if (totalItems == key + 1)
_that.appendToRoot();
})
},
addOne:function( model ){
var storePaymentListItem_View = new StorePaymentListItem_View({ model: model });
this.$wrapper.append( storePaymentListItem_View.el );
},
appendToRoot:function(){
this.$el.html('').append( this.$wrapper );
}
})
My guess is closing the modal doesn't call view.remove, and so we end up with a zombie view that is removed from the DOM but still lives in memory listening to events.
Another guess is you never remove the List_View instance, so they are the zombies.
In other words, this is likely to be related to insufficient garbage collection.
This is a guess - it's impossible to tell without seeing the relevant parts of the code.
Array Of Objects
The data is received from server
var Updates = [
{"post_id":"1","post_desc":"This is my first post",
"comments":[{"id":1,"comment":"some comments","like":7},
{"id":9,"comment":"some comments","like":3}
]
},
{"post_id":"2","post_desc":"This is my second post",
"comments":[{"id":5,"comment":"some comments","like":5}]
}]
Model:
var Update = Backbone.Model.extend({
defaults:{
photo: "default.png"
}
});
Collection:
var latestUpdates = Backbone.Collection.extend({
model: Update
});
Single View:
var UpdateView = Backbone.View.extend({
tagName: "div",
className: "post-container",
template: $("#postTemplate").html(),
render: function () {
var tmpl = _.template(this.template);
this.$el.html(tmpl(this.model.toJSON()));
return this;
}
});
Master view:
var UpdatesView = Backbone.View.extend({
el: $("#postContainer"),
initialize: function () {
this.collection = new latestUpdates(Updates);
this.render();
},
render: function () {
var that = this;
_.each(this.collection.models, function (item) {
that.renderUpdates(item);
}, this);
},
renderUpdates: function (item) {
var updateView = new UpdateView({
model: item
});
this.$el.append(updateView.render().el);
}
});
//create app instance
var wallUpdates = new UpdatesView();
How can I render comments section under each post?
Trying to achieve layout similar to facebook post-comment system
I'd use a CommentListView, owned by your UpdateView. tagName: "ul", className: "post-comments"
Then have a CommentView owned by the CommentListView. CommentView's render should not append anything to the DOM, but return its $el.
CommentListView would tell each of the CommentView's to render, appending each of their $el's to the CommentListView's $el.
For the containers, I'd use:
<div class="post-container" data-post-id="<%= YourPostId %>">
<div class="post-body">
<!--Your post can go in here-->
</div>
<ul class="post-comments">
<!--Append your comments in here-->
</ul>
</div>
I'm displaying a table of categories with Backbone. I created two views:
RowView (containing a single tr)
TableView (containing table structure)
The definitions:
RowView = Backbone.View.extend({
el: "#content table tbody",
initialize: function() {
this.render();
},
render: function(){
var params = { name: this.model.get('name'), route: this.options.route };
var template = _.template( $("#rowTemplate").html(), params);
this.$el.append(template);
},
events: {
"click #name": "clickHandler"
},
clickHandler: function( event ) {
console.log('Browse subcategories of ' + this.model.get('name'));
}
});
TableView = Backbone.View.extend({
el: "#content",
initialize: function(){
this.render();
},
render: function(){
var row = new this.collection();
var that = this;
row.fetch({
success: function() {
console.log('Collection fetch succeeded');
var params = { title: that.options.title,
counter: row.at(0).get('counter'),
route: that.options.route
};
var template = _.template( $("#tableTemplate").html(), params);
that.$el.html( template );
// RowView's are created by iteration here
for(var x = 1; x < row.length; x++) {
var params = { model: row.at(x), route: that.options.route };
var view = new RowView(params);
}
}
});
}
});
As you can see, I've attached a click event at the RowView.
RowView template:
<script type="text/template" id="rowTemplate">
<tr>
<td id="name" class="fill"><%= name %></td>
<td>Editar</td>
</tr>
</script>
Clicking any #name triggers the handler in all instance of the view. So when clicking one category I get:
Browse subcategories of category1 127.0.0.1:68
Browse subcategories of category2 127.0.0.1:68
etc...
As far as I know, that's because all RowView's are delegated to the same el.
The first thing I though about was adding the category name to the rowTemplate and compare the value in the DOM with the value in the view to see which one actually triggers the event.
But that solutions look really ugly. What's the correct way of accomplishing this in Backbone?
EXTRA: Is it considered better if I only create one view, and iterate in the template to generate the rows?
EDIT: I think the provided code is enough. Otherwise I can add them.
you can modify RowView like this :
RowView = Backbone.View.extend({
container: '#content table tbody',
tagName: 'tr',
initialize: function() {
this.render();
},
render: function() {
var params = {
name: this.model.get('name'),
route: this.options.route
};
var template = _.template($("#rowTemplate").html(), params);
this.$el.html(template).appendTo(this.container);
},
events: {
"click .fill": "clickHandler"
},
clickHandler: function(event) {
console.log('Browse subcategories of ' + this.model.get('name'));
}
});
and RowView template:
<script type="text/template" id="rowTemplate">
<td class="fill"><%= name %></td>
<td>Editar</td>
</script>
Backbone.js will create a tr element. then this.$el.html(template).appendTo(this.container) fill the tr element with template and append to #content table tbody.
just like that, RowView's events be delegated on RowView's el, not #content table tbody.
You have more than one element with the same id on your page, due to all of your rows having the
<td id="name" class="fill"> element.
Element IDs should be unique within your document.
One solution would be to distinguish the rows in your template, and use events as a function to set the proper ID.
Template:
<script type="text/template" id="rowTemplate">
<tr>
<td id="name-<%= name %>" class="fill"><%= name %></td>
<td>Editar</td>
</tr>
Events function:
events: function(){
_events = {};
_events["click #name-" + this.model.get('name')] = "clickHandler";
return _events;
}
Try this
RowView = Backbone.View.extend({
container: '#content table tbody',
tagName: 'tr',
// initialize: function() {
// this.render();
// },
render: function() {
var params = {
name: this.model.get('name'),
route: this.options.route
};
var template = _.template($("#rowTemplate").html(), params);
this.$el.append(this.template);
},
events: {
"click .name": "clickHandler"
},
clickHandler: function(event) {
console.log('Browse subcategories of ' + this.model.get('name'));
}
});
RowView template (no need for identifying each row view):
<script type="text/template" id="rowTemplate">
<td class="name"><%= name %></td>
<td>Editar</td>
</script>
Then the table view:
...
that.$el.html( template );
// RowView's are created by iteration here
for(var x = 1; x < row.length; x++) {
var params = { model: row.at(x), route: that.options.route };
var view = new RowView(params);
that.$el.find('tbody').append(view.el);
view.render()
}
...
My understanding of the Backbone View is that each html element that needs to show model data can be a View by itself.
I wish to create view linked to a specific div to show model data.
My problem is that the code doesn't work if I use anything else than 'body' for el.
Following code does not work:
http://jsfiddle.net/GhaPF/9/
$(document).ready(function() {
var ToDo = Backbone.Model.extend({
defaults: { "date": "today",
"task": ""
},
initialize: function() {}
});
var ToDoList = Backbone.Collection.extend({
model: ToDo
});
var ToDoListView = Backbone.View.extend({
el: "#view1",
initialize: function(myTodoList) {
this.todolist = myTodoList;
this.todolist.bind('add', this.render, this);
},
render: function() {
text = this.todolist.toJSON();
string = JSON.stringify(text);
$(this.el).append(string);
return this;
},
events: {
"keypress #new-todo": "createOnEnter"
},
createOnEnter: function(e) {
if (e.keyCode != 13) return;
if (!$("#new-todo").val()) return;
this.todolist.add({"task": $("#new-todo").val()});
$("#new-todo").val('');
}
});
$("#new-todo").focus();
var todolist = new ToDoList();
var myToDoListView = new ToDoListView(todolist);
});
But if I use 'body' for el, it works as I want.
How can I set the el to a specific div ?
solution
http://jsfiddle.net/r3F8q/
you can also use this.setElement('#body1') in render
<div id="view-container">
<input id="new-todo" placeholder="text">
<div id="view1"></div>
<div id="view2"></div>
</div>
$(document).ready(function() {
var ToDo = Backbone.Model.extend({
defaults: { "date": "today",
"task": ""
},
initialize: function() {}
});
var ToDoList = Backbone.Collection.extend({
model: ToDo
});
var ToDoListView = Backbone.View.extend({
el: "#view-container",
initialize: function(myTodoList) {
this.todolist = myTodoList;
this.todolist.bind('add', this.render, this);
},
render: function() {
text = this.todolist.toJSON();
string = JSON.stringify(text);
this.$el.find('#view1').append(string);
return this;
},
events: {
"keypress #new-todo": "createOnEnter"
},
createOnEnter: function(e) {
if (e.keyCode != 13) return;
if (!$("#new-todo").val()) return;
this.todolist.add({"task": $("#new-todo").val()});
$("#new-todo").val('');
}
});
$("#new-todo").focus();
var todolist = new ToDoList();
var myToDoListView = new ToDoListView(todolist);
});
When you use "#view1"
"keypress #new-todo": "createOnEnter"
is not binded, because #new-todo is not within "#view1". Check API.
I am putting together a backbone example in which models are created edited and deleted. I am able to save new models and edits to local storage, but am having a problem getting localstorage to properly display on refresh. It seems to be loading as a single object, and therefore gives me one model regardless of how many were added.
var Thing = Backbone.Model.extend({
defaults: {
title: 'blank'
}
});
var ThingView = Backbone.View.extend({
template: _.template('<b><button id="remove">X</button> <b><button id="edit">Edit</button> <%= title %></b>'),
editTemplate: _.template('<input class="name" value="<%= name %>" /><button id="save">Save</button>'),
events: {
"click #remove": "deleteItem",
"click #edit": "editItem",
"click #save": "saveItem",
},
deleteItem: function () {
console.log('deleted');
this.model.destroy();
this.remove();
},
editItem: function () {
console.log('editing');
this.$el.html(this.editTemplate(this.model.toJSON()));
},
saveItem: function () {
console.log('saved');
editTitle = $('input.name').val();
console.log(editTitle);
this.model.save({
title: editTitle
});
this.$el.html(this.template(this.model.toJSON()));
},
render: function () {
var attributes = this.model.toJSON();
this.$el.append(this.template(attributes));
return this;
}
});
var ThingsList = Backbone.Collection.extend({
model: Thing,
localStorage: new Store("store-name"),
});
var storeVar = localStorage.getItem("store-name");
console.log(storeVar);
var thingsList = new ThingsList;
thingsList.reset(storeVar);
var ThingsListView = Backbone.View.extend({
el: $('body'),
events: {
'click #add': 'insertItem',
},
initialize: function () {
this.render();
this.collection.on("add", this.renderThing, this);
},
insertItem: function (e) {
newTitle = $('input').val();
newThing = new Thing({
title: newTitle
});
this.collection.add(newThing);
newThing.save();
console.log(this.collection.length);
},
render: function () {
_.each(this.collection.models, function (items) {
this.renderThing(items);
}, this);
},
renderThing: function (items) {
var thingView = new ThingView({
model: items
});
this.$el.append(thingView.render().el);
}
});
var thingsListView = new ThingsListView({
collection: thingsList
});
You need to add the items to your collection, and then to read it in you need to call fetch. You also have a couple of extra trailing commas in your objects.
Here's a slightly modified version of your code which seems to work.
var Thing = Backbone.Model.extend({
defaults:{
title:'blank'
}
});
var ThingView = Backbone.View.extend({
//el: $('body'),
template: _.template('<b><button id="remove">X</button> <b><button id="edit">Edit</button> <%= title %></b>'),
editTemplate: _.template('<input class="name" value="<%= name %>" /><button id="save">Save</button>'),
events: {
"click #remove": "deleteItem",
"click #edit": "editItem",
"click #save": "saveItem",
},
deleteItem: function(){
console.log('deleted');
this.model.destroy();
//remove view from page
this.remove();
},
editItem: function(){
console.log('editing');
this.$el.html(this.editTemplate(this.model.toJSON()));
},
saveItem: function(){
console.log('saved');
editTitle = $('input.name').val();
console.log(editTitle);
this.model.save({title: editTitle});
this.$el.html(this.template(this.model.toJSON()));
},
render: function(){
var attributes = this.model.toJSON();
this.$el.append(this.template(attributes));
return this;
}
});
var storeVar = localStorage.getItem("store-name");
var ThingsList = Backbone.Collection.extend({
model: Thing,
localStorage: new Store("store-name")
});
var things = [
{ title: "Macbook Air", price: 799 },
{ title: "Macbook Pro", price: 999 },
{ title: "The new iPad", price: 399 },
{ title: "Magic Mouse", price: 50 },
{ title: "Cinema Display", price: 799 }
];
console.log(things);
var thingsList = new ThingsList;
var ThingsListView = Backbone.View.extend({
el: $('body'),
events: {
'click #add': 'insertItem'
},
initialize: function () {
this.render();
this.collection.on("add", this.renderThing, this);
},
insertItem: function(e){
newTitle = $('input').val();
newThing = new Thing({ title: newTitle });
this.collection.add(newThing);
newThing.save();
//this.model.saveItem;
console.log(this.collection.length);
},
render: function(){
_.each(this.collection.models, function (items) {
this.renderThing(items);
}, this);
},
renderThing: function(items) {
//console.log('added something');
var thingView = new ThingView({ model: items });
items.save();
this.$el.append(thingView.render().el);
}
});
var thingsListView = new ThingsListView( {collection: thingsList} );
thingsList.fetch();
console.log(thingsList.toJSON());
thingsList.reset(things);
Edit: I see you are trying to read in the value stored in local storage under "store-name", the way backbone-localStorage works is that it uses the name of the store (in your case "Store-name") to store the ids of the rest of the models and then saves each model under a combination of the store name and the id, so say you had three models, you would end up with 4 entries in local storage,
localStorage["store-name"] //id1, id2, id3"
localStorage["store-name-id1"] //model with id1
localStorage["store-name-id2"] // model with id2
localStorage["store-name-id3"] // model with id3
EDIT 2
Here's a link to a jsfiddle of your code, to start I'm leaving the line thingsList.fetch(); commented out, uncomment that line and comment out thingsList.add(things); and run it a second time and it should pull the models from local Storage (I left an alert in there).
var Thing = Backbone.Model.extend({
defaults: {
title: 'blank'
}
});
var ThingView = Backbone.View.extend({
template: _.template('<b><button id="remove">X</button> <b><button id="edit">Edit</button> <%= title %></b>'),
editTemplate: _.template('<input class="name" value="<%= name %>" /><button id="save">Save</button>'),
events: {
"click #remove": "deleteItem",
"click #edit": "editItem",
"click #save": "saveItem",
},
deleteItem: function () {
console.log('deleted');
this.model.destroy();
this.remove();
},
editItem: function () {
console.log('editing');
this.$el.html(this.editTemplate(this.model.toJSON()));
},
saveItem: function () {
console.log('saved');
editTitle = $('input.name').val();
console.log(editTitle);
this.model.save({
title: editTitle
});
this.$el.html(this.template(this.model.toJSON()));
},
render: function () {
var attributes = this.model.toJSON();
this.$el.append(this.template(attributes));
return this;
}
});
var ThingsList = Backbone.Collection.extend({
model: Thing,
localStorage: new Store("store-name"),
});
var storeVar = localStorage["store-name-7ee7d1e3-bbb7-b3e4-1fe8-124f76c2b64d"];
console.log(storeVar);
var thingsList = new ThingsList;
//thingsList.reset(storeVar);
var ThingsListView = Backbone.View.extend({
el: $('body'),
events: {
'click #add': 'insertItem',
},
initialize: function () {
thingsList.fetch();
thingsList.toJSON();
this.render();
this.collection.on("add", this.renderThing, this);
},
insertItem: function (e) {
newTitle = $('input').val();
newThing = new Thing({
title: newTitle
});
this.collection.add(newThing);
newThing.save();
console.log(this.collection.length);
},
render: function () {
_.each(this.collection.models, function (items) {
this.renderThing(items);
}, this);
},
renderThing: function (items) {
var thingView = new ThingView({
model: items
});
this.$el.append(thingView.render().el);
}
});
var thingsListView = new ThingsListView({
collection: thingsList
});