How can we do paging with backbone marionette composite view? - backbone.js

I am new to backbone and marionette. Now i m trying to implement paging with compositeview of marionettejs. Below is my code, what happens here that when a new fetch is done through my custom pager, existing data is getting replaced by new set of data instead of appending. Please help me to overcome this! Thanks in advance.
define(['text!/Templates/projects/_GroupItem.html', 'collections/projects/groups'], function (ProjectGroupsTmpl, GroupCollection) {
var GroupItemView = Backbone.Marionette.ItemView.extend({
tagName: 'li',
template: _.template(ProjectGroupsTmpl)
});
var CompositeView = Backbone.Marionette.CompositeView.extend({
template: _.template("<ul id='ulgroups' ></ul>"),
itemView: GroupItemView,
itemViewContainer: '#ulgroups',
initialize: function (params) {
this.isLoading = false;
this.ProjectID = params.id;
this.collection = new GroupCollection();
this.getData();
var self = this;
$(window).scroll(function () {
self.checkScroll();
});
},
getData: function () {
var that = this;
this.isLoading = true;
this.collection.fetch({
data: { ProjectID: this.ProjectID },
success: function (collection, response, options) {
that.isLoading = false;
}
});
},
checkScroll: function () {
var triggerPoint = 100; // 100px from the bottom
if (!this.isLoading && $(window).scrollTop() + $(window).height() + triggerPoint > $(document).height()) {
this.collection.page += 1; // Load next page
this.getData();
}
},
appendHtml: function (collectionView, itemView, index) {
$(this.itemViewContainer).append(itemView.el);
}
});
return CompositeView;
});

I have used backbone.paginator to resolve above issue and it works well. Below are the new code used for that.
Collection:
define([
'jquery',
'underscore',
'backbone',
'helper',
'paginator'
], function ($, _, Backbone) {
var Groups = Backbone.PageableCollection.extend({
url: 'projects/_groups',
mode: "infinite",
state: {
pageSize: null
},
queryParams: {
totalPages: null,
totalRecords: null
}
});
return Groups;
});
Marionette CompositeView:
define(['text!/Templates/projects/_GroupItem.html', 'collections/projects/groups'], function (ProjectGroupsTmpl, GroupCollection) {
var GroupItemView = Backbone.Marionette.ItemView.extend({
tagName: 'li',
template: _.template(ProjectGroupsTmpl)
});
var CompositeView = Backbone.Marionette.CompositeView.extend({
template: _.template("<ul id='ulgroups' ></ul>"),
itemView: GroupItemView,
itemViewContainer: '#ulgroups',
initialize: function (params) {
this.isLoading = false;
this.ProjectID = params.id;
this.grpcollection = new GroupCollection([], {
queryParams: {
ProjectID: params.id
}
});
this.collection = this.grpcollection.fullCollection;
this.getData();
var self = this;
$(window).scroll(function () {
self.checkScroll();
});
},
getData: function () {
var that = this;
this.isLoading = true;
this.grpcollection.fetch({
success: function (collection, response, options) {
if (response.length > 0) {
that.isLoading = false;
}
}
});
},
getNextPage: function () {
var that = this;
this.isLoading = true;
this.grpcollection.getNextPage({
success: function (collection, response, options) {
if (response.length > 0) {
that.isLoading = false;
}
}
});
},
checkScroll: function () {
var triggerPoint = 100; // 100px from the bottom
if (!this.isLoading && $(window).scrollTop() + $(window).height() + triggerPoint > $(document).height()) {
this.getNextPage();
}
},
appendHtml: function (collectionView, itemView, index) {
$(this.itemViewContainer).append(itemView.el);
}
});
return CompositeView;
});

I solved a similar problem recently by creating a temporary collection to hold the models for each paginated request. My setup was slightly different to yours, however, in that I created a Marionette controller to negotiate between the data and the view. A "show" method on the controller handled the initial data request and a "showMore" method handled subsequent requests. Here is basically what I did:
(function ($, _, Backbone, Marionette) {
var carData = [
{
make: 'Audi',
model: 'A4',
year: '1994'
},
{
make: 'BMW',
model: '3 Series',
year: '1975'
},
{
make: 'Chevrolet',
model: 'Cruze',
year: '2008'
},
{
make: 'Daimler',
model: 'Six',
year: '1994'
},
{
make: 'Fiat',
model: '500X',
year: '2015'
},
{
make: 'Honda',
model: 'Civic',
year: '1972'
},
{
make: 'Kia',
model: 'Optima',
year: '2015'
},
{
make: 'Lada',
model: 'Priora',
year: '2007'
},
{
make: 'Mitusbishi',
model: 'Lancer',
year: '1973'
},
{
make: 'Nissan',
model: 'Pathfinder',
year: '1995'
}
];
var Car = Backbone.Model.extend({
defaults: {
make: '',
model: '',
year: ''
}
});
var Cars = Backbone.Collection.extend({
model: Car,
rows: 3,
page: 0
});
var CarView = Marionette.ItemView.extend({
tagName: 'tr',
template: '#row-template'
});
var CarsView = Marionette.CompositeView.extend({
childView: CarView,
childViewContainer: 'tbody',
template: '#table-template',
triggers: {
'click button': 'showMore'
}
});
var CarController = Marionette.Controller.extend({
initialize: function (options) {
this.collection = options.collection;
},
show: function () {
var cars = this.getData(this.collection.page);
var carsView = new CarsView({
collection: new Backbone.Collection(cars)
});
this.listenTo(carsView, 'showMore', this.showMore);
app.carsRegion.show(carsView);
},
showMore: function (options) {
var cars = this.getData(++this.collection.page);
options.collection.add(cars);
},
getData: function (page) {
var rows = this.collection.rows;
var start = page * rows;
var end = start + rows;
return this.collection.slice(start, end);
}
});
var app = new Marionette.Application();
var cars = new Cars(carData);
var carController = new CarController({
collection: cars
});
app.addRegions({
carsRegion: '#cars-region'
});
app.addInitializer(function () {
carController.show();
});
app.start();
}(jQuery, _, Backbone, Marionette));
This is also available as a JSFiddle.

Related

Backboe memory leak in subviews

I still strugling with memory leak in my app. I wannted to do it without huge changes in code.
var ItemsView = Backbone.View.extend({
id:'products', // If I change it to el: document.getElementById('products') and without passing views into items object, my views are properly rendered but with memory leak
events: { },
initialize: function() {
_.bindAll(this);
this.listenTo(this.collection, 'reset', this.reset);
this.listenTo(this.collection, 'add', this.addItem);
this.listenTo(this.collection, 'change', this.changeItem);
this.listenTo(this.collection, 'destroy', this.delItem);
this.items = [];
},
reset: function(){ console.log("reset");
this.el.innerHTML = null;
this.render();
},
render: function(){
for(var i=0; i < this.collection.length; i++){
this.renderItem(this.collection.models[i]);
}
},
renderItem: function( model ){
var itemView = new ItemView({ model: model });
itemView.render();
this.items.push(itemView);
jBone(this.el).append(itemView.el);
},
addItem: function(){ console.log("addItem");
this.renderItem();
},
changeItem: function(){ console.log("changeItem"); },
delItem: function(){ console.log("delItem"); },
remove: function() {
_.invoke(this.items, 'remove');
this.items = [];
Backbone.View.prototype.remove.call(this);
}
});
return ItemsView;
This is my Itemsview it is executed when user hit orderview, there is created ItemView for every model in collection:
var ItemView = Backbone.View.extend({
tagName: "li",
className: "productcc",
initialize: function () {
_.bindAll(this, 'addItem', 'removeItem', 'updateItem');
this.listenTo(this.model, 'remove', this.removeItem);
this.listenTo(this.model, 'change', this.updateItem);
},
events: {},
render: function () {
var model = this.model.toJSON();
this.el.innerHTML += '<div class="tabody"><h4 class="tablename">'+model.title+'<h4>'+model.status+'</div>';
return this;
},
addItem: function(){
this.collection.create({"table_no":"demo"});
},
changeItem: function(e){
e.preventDefault();
this.model.save({ table_no: 'demo' });
},
updateItem: function(newstuff){
console.log("updateItem");
console.log(this.el);
},
delItem: function(){
this.model.destroy({ silent: true });
},
removeItem: function(model){
console.log("removeItem");
console.log(model);
var self = this;
self.el.remove();
}
});
return ItemView;
MY ROUTER:
var AppRouter = Backbone.Router.extend({
routes: {
'' : 'home',
'home' : 'home',
'customer/:customer_id': 'showItems'
}
});
var initialize = function(options) {
window.app_router = new AppRouter;
window.socket = io.connect('www.example.com');
this.socketOrdersCollection = new SocketOrdersCollection();
this.ordersView = new OrdersView({ collection: this.socketOrdersCollection });
this.socketOrdersCollection.fetch({ reset: true });
app_router.on('route:home', function() { });
app_router.on('route:showItems', function(customer_id) {
if (this.itemsView) {
this.itemsView.remove();
}
this.socketItemsCollection = new SocketItemsCollection();
this.socketItemsCollection.fetch({ data: { id: customer_id}, reset: true });
this.itemsView = new ItemsView({
collection: this.socketItemsCollection,
model: { tableName: customer_id }
});
});
Backbone.history.start();
};
I have to remove also ItemsView after click to another order...
Thanks for any opinion.
Ok. Let me take a stab at what you're attempting here.
var ItemsView = Backbone.View.extend({
el: document.getElementById('products'),
events: { },
initialize: function() {
// everything you had before
this.items = [];
},
// etc.
renderItem: function( model ){
var itemView = new ItemView({ model: model });
itemView.render();
this.items.push(itemView);
jBone(this.el).append(itemView.el);
},
// etc.
// we're overloading the view's remove method, so we clean up our subviews
remove: function() {
_.invoke(this.items, 'remove');
this.items = [];
Backbone.View.prototype.remove.call(this);
}
});
return ItemsView;
And then in the router:
var initialize = function(options) {
// etc.
app_router.on('route:home', function() { });
app_router.on('route:showItems', function(customer_id) {
if (this.itemsView) {
this.itemsView.remove();
}
// everything else the same
});
Backbone.history.start();
};
So now, your ItemsView will clean up any child items it has, and when you change customers, you'll clean up any ItemsView you have open before generating a new one.
EDIT
I see what you're having a problem with now.
In your route handler, you're going to need to do something along these lines:
app_router.on('route:showItems', function(customer_id) {
// everything you already have
jBone(document.getElementById('container')).append(this.itemsView);
});

Nested CompositeViews with different sources instantiate multiple parent views instead of child

I have three views in my application. One ItemView (item) which is a child of CompositeView (category) which is a child of CompositeView (parentCategory).
I also waterfall instantiate my views based on API hits from data (in this case I'm using local data to give the impression of live data).
Here is my application in js form:
var App = new Backbone.Marionette.Application();
App.addRegions({
mainRegion: "#main"
});
var todoArray = [];
// A single row
var TodoRow = Backbone.Marionette.ItemView.extend({
template: "#todo-template",
tagName: "li",
events: {
'click span': 'clickSpan'
},
clickSpan: function() {
console.log(this);
}
});
// The grid view
var CategoryView = Backbone.Marionette.CompositeView.extend({
tagName: "li",
template: "#category-template",
itemView: TodoRow,
itemViewOptions: function(model, index) {
return {
parent: model.get('parent')
}
},
appendHtml: function(collectionView, itemView){
if(collectionView.id === itemView.model.get('parent')) {
itemView.render();
collectionView.$("ul.items").append(itemView.el);
}
}
});
var TabView = Backbone.Marionette.CompositeView.extend({
tagName: "li",
template: "#tab-template",
itemView: CategoryView,
itemViewOptions: function(model, index) {
return {
parent: model.get('parent')
}
},
appendHtml: function(collectionView, itemView){
if(collectionView.id === itemView.model.get('parent')) {
itemView.render();
collectionView.$("ul.categories").append(itemView.el);
}
}
});
var Tab = Backbone.Model.extend({}),
Category = Backbone.Model.extend({}),
Todo = Backbone.Model.extend({});
var TabCollection = Backbone.Collection.extend({
model: Tab,
url: 'tab.json'
});
var CategoryCollection = Backbone.Collection.extend({
model: Category,
url: 'category.json'
});
var TodoCollection = Backbone.Collection.extend({
model: Todo,
url: 'todo.json'
});
var todoList,
todoFetch,
categoryList,
categoryFetch,
tabList,
tabFetch;
App.addInitializer(function() {
console.log(data);
todoList = new TodoCollection(data.items);
todoFetch = todoList.fetch();
categoryList = new CategoryCollection(data.categories);
tabList = new TabCollection(data.tabs);
var todoCallback = function() {
//categoryFetch = categoryList.fetch();
//categoryFetch.done(categoryCallback);
categoryCallback();
},
categoryCallback = function() {
//tabFetch = tabList.fetch();
//tabFetch.done(tabCallback);
tabCallback();
},
tabCallback = function() {
tabList.each(function(tab, index) {
var sampleCatList = _.filter(categoryList.models, function(category) {
if(tab.get('id') === category.get('parent')) return true;
return false;
});
tabView = new TabView({
collection: new TabCollection(sampleCatList),
id: tab.get('id'),
model: tab
});
tabView.render();
$('#main ul').append(tabView.el);
});
};
//todoFetch.done(todoCallback);
todoCallback();
});
App.start();
I have a working JSFiddle here: http://jsfiddle.net/Pq5s7/
There should be three two level li's Roger & Wilko
Then there should be two categories, and one item underneath each category.

BackboneJS - Cannot call method 'on' of undefined

I have this simple BackboneJS app and it keeps returning this error on adding new model to collection: Cannot call method 'on' of undefined. Can someone help me. I can't see the problem in here.I have my templates defined in index.html, and I am using Slim framework and NotORM.
(function(){
window.App =
{
Models:{},
Collections: {},
Views : {}
}
window.template = function(id)
{
return _.template( jQuery('#' + id).html());
}
App.Models.Party = Backbone.Model.extend({
});
App.Collections.Partys = Backbone.Collection.extend({
model: App.Models.Party,
url: "http://localhost/BackboneJS/vjezba6/server/index.php/task"
});
App.Views.Party = Backbone.View.extend({
tagName :"div",
className: "box shadow aktivan",
template: template("boxovi"),
initialize: function()
{
this.model.on('change', this.render, this);
},
events:{
"click .izbrisi" : "izbrisi"
},
render: function()
{
var template = this.template( this.model.toJSON() );
this.$el.html(template);
return this;
},
izbrisi: function()
{
this.model.destroy();
},
ukloni: function()
{
this.remove();
}
});
App.Views.Partys = Backbone.View.extend({
tagName:"div",
id: "nosac-boxova",
initialize: function()
{
},
render: function() {
this.collection.each(this.addOne, this);
return this;
},
addOne: function(party) {
var partyView = new App.Views.Party({ model: party });
this.$el.append(partyView.render().el);
}
});
App.Views.Dodaj = Backbone.View.extend({
tagName: "div",
template : template("dodajTemp"),
events:
{
'submit' : 'submit'
},
submit : function(e)
{
e.preventDefault();
console.log(e);
var nazivPolje = $(e.currentTarget).find(".naziv").val();
var tekstPolje = $(e.currentTarget).find(".lokal").val();
var noviParty = new App.Views.Party({naziv:nazivPolje, tekst: tekstPolje});
this.collection.create(noviParty);
},
initialize: function()
{
},
render: function()
{
var template = this.template();
this.$el.html(template);
return this;
}
});
/* var kolekcijaPartya = new App.Collections.Partys([
{
naziv:"Ovo je prvi naziv",
tekst: "Ovo je prvi tekst"
},
{
naziv:"Ovo je drugi naziv",
tekst: "Ovo je drugi tekst"
}
]);*/
var kolekcijaPartya = new App.Collections.Partys;
kolekcijaPartya.fetch({
success: function()
{
var partysView = new App.Views.Partys({collection:kolekcijaPartya});
$("#content").prepend(partysView.render().el);
$("div.box").slideAj();
var dodajView = new App.Views.Dodaj({collection: kolekcijaPartya});
$("div#sidebar-right").html(dodajView.render().el);
}
});
})();
var noviParty = new App.Views.Party({naziv:nazivPolje, tekst: tekstPolje});
this.collection.create(noviParty);
so you are trying to add a View to your collection?

backbone-extend.js doesn't seem to load my method

I added this to my backbone-extend.js file which resides in the same folder as backbone-min.js...
_.extend(Backbone.View.prototype, {
getFormData: function(form) {
var unindexed_array = form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});
return indexed_array;
}
});
However, when I call this.getFormData in my view code, I get a method not defined error. What am I missing? Thanks for your help!
Edit: Here is my view. I have to uncomment the getFormData method to make it work. It can't see the getFormData otherwise...
define([
'jquery',
'underscore',
'backbone',
'models/Member',
'text!templates/memberEditTemplate.html'
], function($, _, Backbone, Member, memberEditTemplate) {
var MemberEditView = Backbone.View.extend({
el: $("#page"),
model: 'member',
initialize: function(args) {
this.member = new Member({ id: args.id });
this.member.on('error', this.eventSyncError, this);
this.member.on('sync', this.eventSyncModelLoaded, this);
this.member.fetch();
},
events: {
"click #bttnMemberSave": "bttnClickMemberSave"
},
eventSyncError: function(model,response,options) {
console.log('Sync error='+response.statusText);
$('#server-message').css({'color':'red', 'font-weight':'bold'}).text(response.statusText);
//$('#server-message').text(response.statusText);
},
eventSyncModelLoaded: function(model,response,options) {
this.render();
},
eventSyncModelSaved: function(model,response,options) {
console.log("Member saved!");
$('#server-message').css({'color':'green', 'font-weight':'bold'}).text("Member saved!");
//$('#server-message').text('Member saved!');
var to = setTimeout(function() { Backbone.history.navigate('members', true); }, 2000);
},
bttnClickMemberSave: function() {
var data = this.getFormData($('#member-form').find('form'));
this.member.save(data, { success: this.eventSyncModelSaved });
},
// getFormData: function(form) {
// var unindexed_array = form.serializeArray();
// var indexed_array = {};
// $.map(unindexed_array, function(n, i){
// indexed_array[n['name']] = n['value'];
// });
// return indexed_array;
// },
render: function() {
this.member.toJSON();
var compiledTemplate = _.template( memberEditTemplate, { member: this.member } );
this.$el.html( compiledTemplate );
return this;
}
});
return MemberEditView;
});
Ok, I added backbone-extend.js to the RequireJS required files array in my app.js, now it's working.

using localStorage in Backbone.js

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

Resources