Call method in collection, when View's method called - backbone.js

I have a view and collection like this:
window.DmnView = Backbone.View.extend({
template: _.template($("#tmpl_dmnListItem").html()),
events: {
"click .getWhois": "showWhois",
"click .getDomain": "toBasket"
},
initialize: function() {
this.model.bind('change', this.render, this);
this.model.bind('destroy', this.remove, this);
},
render: function() {
return $(this.el)
.attr("class", this.model.get("free") ? "dmnItem green" : this.model.get("checked") ? "dmnItem red" : "dmnItem red loader")
.html(this.template(this.model.toJSON()));
},
remove: function() {
$(this.el).remove();
},
showWhois: function() {
showBoxes(this.model.get("info"));
return false;
},
toBasket: function() {
this.model.toBasket();
console.log("view");
}
});
window.DmnListApp = Backbone.View.extend({
el: $("#regWrap"),
events: {
"keypress #dmnName": "checkAll"
},
initialize: function() {
this.input = this.$("#dmnName");
this.list = this.$("#dmnList");
this.basket = this.$("#dmnBasket");
dmnList.bind('add', this.addOne, this);
dmnList.bind('all', this.render, this);
DmnView.bind('toBasket', this.toBasket, this);
},
render: function() {
},
addOne: function(dmnItem) {
var view = new DmnView({model : dmnItem});
this.list.append(view.render());
},
checkOne: function(name, zone, price, days) {
dmnList.create({name: name, zone: zone, price: price, days: days});
},
checkAll: function(e) {
var name = this.input.val();
if (!name || e.keyCode != 13) return;
if (name == "")
name = "yandex";
dmnList.destroyAll();
var zoneList = dmnList.domainsInfo.Name;
var costList = dmnList.domainsInfo.CostOrder;
var daysList = dmnList.domainsInfo.DaysToProlong;
var parent = this;
$.each(zoneList, function(key, zone) {
parent.checkOne(name, zone, costList[key], daysList[key]);
});
this.input.val("");
},
toBasket: function(){
console.log("collection");
}
});
I want Collection's method toBasket() to be called after View's method toBasket() was called. For this purpose I do the following in Collection:
DmnView.bind('toBasket', this.toBasket, this);
So, if this worked, I should receive two messages in my javascript console:
view
collection
(Maybe in other order)
But I only see "view" message in console. What I do wrong?
TIA!

You're almost there. In your collection view, you're attempting to listen to the DmnView event toBasket, but how you have it setup is a little incorrect. To listen to events, you have to bind to a specific instance you want to listen to, not a class. So you'll want to move the bind from initialize to addOne, like this:
window.DmnListApp = Backbone.View.extend({
// ...
initialize: function() {
this.input = this.$("#dmnName");
this.list = this.$("#dmnList");
this.basket = this.$("#dmnBasket");
dmnList.bind('add', this.addOne, this);
dmnList.bind('all', this.render, this);
// Remove the DmnView bind here
},
addOne: function(dmnItem) {
var view = new DmnView({model : dmnItem});
// Bind to the DmnView instance here
view.bind('toBasket', this.toBasket, this);
this.list.append(view.render());
},
// ...
});
Now that your collection view is listening for the event toBasket, you need to actually fire the event in your DmnView view.
In Backbone views, no events are automatically fired, so you'll need to manually trigger it yourself, like this:
window.DmnView = Backbone.View.extend({
// ...
toBasket: function() {
this.model.toBasket();
console.log("view");
// Trigger the event
this.trigger('toBasket');
}
});
You should now see both messages in your console.

Related

backbone fetch collection on infinite scroll

I'm learning backbone and now thinking of how to apply an infinite scroll and fetch/load lets say 20 items from my collection every time the scroll is at the bottom of the page.
I have been searching around a lot after different libs and such without really getting any closer. Anyone that can explain/show how this is best done?
I have now added the infiniscroll.js plugin and trying to get it to work. But on scroll it won't load new items. What am i supposed to do on the appendRender? and how?
var StartView = Backbone.View.extend({
tagName: "section",
id: "start",
className: "content",
events: {
},
initialize: function(){
$(".container").html(this.el);
console.log("init start");
this.template = _.template($("#start_template").html(), {} );
this.collection = new VideoCollection();
_.bindAll(this, "render");
this.render();
this.infiniScroll = new Backbone.InfiniScroll(this.collection, {
success: this.appendRender,
pageSize: this.collection.length,
scrollOffset: 100
});
},
appendRender: function() {
var self = this;
self.$el.html(self.template);
self.$el.find(".videos").append("<div style='margin-bottom:30px; width:100%; height:170px; float:left; background-color:#e4e4e4;'>fff</div>")
},
render: function(){
var self = this;
this.$el.html("loading");
console.log("render start")
},
kill: function() {
console.log("kill start");
this.remove();
}
});
return StartView;
The backbone-pageable plugin supports infinite scrolling.
It's just a matter of your collection extending Backbone.PageableCollection, and you specifying some extra properties. There's also an example of a backbone view listening to the changing collection, as well as fetching on scroll.
It's all described on the github page. It's updated fairly often.
I would have done it something like this (although the document.addEventListener('scroll')-part isn't really elegant
(function() {
"use strict";
var Item = Backbone.Model.extend({});
var Items = Backbone.Collection.extend({
model: Item,
url: "/api/items/"
});
var ItemView = Backbone.View.extend({
tagName: "li",
render: function() {
this.$el.html(this.model.get("name"));
return this;
}
});
var ItemsList = Backbone.View.extend({
tagName: "ul",
offset: 0,
limit: 60,
initialize: function() {
this.collection = new Items();
this.collection.on("reset", this.addAll, this);
this.collection.on("add", this.addOne, this);
this.getItems();
},
render: function () {
return this;
},
getItems: function () {
this.collection.fetch({
"data": {"offset": this.offset, "limit": this.limit},
"success": _.bind(function(e){
this.offset += this.limit;
}, this)
});
},
addOne: function(item) {
var view = new ItemView({model: item});
this.$el.append(view.render().$el);
},
addAll: function() {
this.collection.each(this.addOne, this);
}
});
var itemsList = new ItemsList();
$(document.body).append(itemsList.render().$el);
document.addEventListener('scroll', function (event) {
if (document.body.scrollHeight == document.body.scrollTop + window.innerHeight) {
itemsList.getItems();
}
});
}());

Multiple Views and Sub Views with 1 collection in Backbone

I have issue in rendering Shopping Bag Views using Backbone for my website.
I am using 1 collection for all Bag Views (“Quick_View” of items list & “Normal_View” of Items list). Also I created “Item_View”, which is being used to render each item in both the Views.
It is a SPA (Single Page Application) and “Quick_View” is initiated and rendered for all Backbone routes and hidden by default. Whenever user clicks on “Quick_View” link from any page it is showing. There is no route defined for it.
The “Normal_View”, can be accessed using Checkout button given in “Quick_View”. It is bind with “domain/checkout” route.
When I access “Normal_View” from “Quick_View” check button; it works fine and both (Quick and Normal) views are in Sync. Means, when we add, delete, update any item in any of the View, both Views are getting updated accordingly.
But when I access “domain/checkout” route directly in a new browser, both views are getting rendered fine, but they are not in sync. Means, change in 1 view does not update another view.
The reason, I tracked is, when I access “Normal_View” through “Quick_View”, model for each item in both the Views having same CID, so the both Views are in sync, if there is any change in a model from any of the View.
And, when I access “Normal_View” directly, model for each item in both the views are not having same CID, so they do not work as expected.
There are few more points to consider:
Collection is firing reset event twice for “Quick_View” and each item
in “Quick_View” is rendering twice.
When, I access “Normal_View” (in either way), “Quick_View” is again getting rendered but once “Normal_View” rendering is over.
// Main View
var mainView = Backbone.View.extend({
el: 'body',
template: {
header: Handlebars.compile(headerTemplate),
mainNav: Handlebars.compile(mainNavtemplate),
footer: Handlebars.compile(footerTemplate)
},
initialize: function() {
_.bindAll();
AW.collection.bag = new bagCollection();
//AW.collection.bag.fetch({reset:true});
},
render: function() {
this.$el.html(this.template());
this.loadSubView('bagQV');
},
loadSubView: function(subView) {
switch(subView) {
case 'home' :
if(!AW.view.home) AW.view.home = new homepageView();
AW.view.home.render();
break;
case 'bagQV' :
if(!AW.view.bagQV) AW.view.bagQV = new bagQuickView({collection: AW.collection.bag});
//AW.view.bagQV.render();
break;
case 'checkout' :
if(!AW.view.checkout) AW.view.checkout = new checkoutView({collection: AW.collection.bag});
AW.view.checkout.render();
break;
}
}
});
// Single Item View
var bagItemView = Backbone.View.extend({
tagName: 'tr',
template: Handlebars.compile(bagItemTemplate),
initialize: function() {
_.bindAll(this);
this.listenTo(this.model, 'change', this.render);
this.listenTo(this.model, 'remove', this.removeItem);
$(document).on('keyup', this.listenKeyboard);
},
events: {
'click .qtyInput .button' : 'updateItem',
'click .controls a.remove' : 'removeModel'
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
this.$el.attr('data-id',this.model.cid);
return this;
},
updateItem: function(e) {
e.preventDefault();
e.stopPropagation();
var newQty = this.$el.find('.qtyInput input').val();
var newAmt = newQty * parseFloat(this.model.get('prodRate').replace('$',''));
this.model.set({prodQty: newQty, amount: '$' + newAmt});
this.cancelEdit(e);
},
removeModel: function(e) {
e.preventDefault();
e.stopPropagation();
if(AW.collection.bag) AW.collection.bag.remove(this.model);
},
removeItem: function() {
this.$el.remove();
}
});
// Bag Quick View
var bagQuickView = Backbone.View.extend({
tagName: 'div',
id: 'myBagQV',
template: Handlebars.compile(bagQuickViewTemplate),
initialize: function() {
_.bindAll(this);
this.collection.fetch({reset:true});
//this.collection.bind("reset", _.bind(this.render, this));
this.listenTo(this.collection, 'add', this.addItem);
this.listenTo(this.collection, 'reset', this.render);
},
render: function() {
if($('#myBagQV').length == 0) {
this.$el.html(this.template());
$('body').append(this.el);
}
this.addAllItems();
return this;
},
addItem: function(item) {
var parent = this;
var itemView = new bagItemView({model: item});
$('#itemsInBag table tbody').append(itemView.render().el);
},
addAllItems: function() {
if(this.collection.length > 0) {
$('#itemsInBag table tbody').html('');
this.collection.each(this.addItem, this);
}
},
});
// Normal Bag View
var bagView = Backbone.View.extend({
tagName: 'div',
id: 'myBag',
template: Handlebars.compile(checkoutBagTemplate),
initialize: function() {
_.bindAll(this);
this.collection.fetch({reset:true});
//this.collection.bind("reset", _.bind(this.render, this));
this.listenTo(this.collection, 'add', this.addItem);
this.listenTo(this.collection, 'reset', this.render);
},
render: function() {
this.$el.html(this.template());
$('#checkoutContainer #details').append(this.el);
this.addAllItems();
return this;
},
addItem: function(item) {
var parent = this;
var itemView = new bagItemView({model: item});
this.$el.find('table tbody').append(itemView.render().el);
},
addAllItems: function() {
if(this.collection.length > 0) {
this.$el.find('table tbody').html('');
this.collection.each(this.addItem, this);
}
}
});
Looking for you help.
Thank you in advance
Cheers,
Vikram

Calling destroy on collection

I am doing a sample application similar to the Backbone-Todo. But when I am invoking destroy on collection it's giving error:
Uncaught TypeError: Cannot read property 'destroy' of undefined
How can I solve this problem. Please suggest.
Following is my method code:
$(function(){
var Todo = Backbone.Model.extend({
defaults: function() {
return {
title: "empty todo...",
order: Todos.nextOrder(),
done: false
};
}
});
var TodoList = Backbone.Collection.extend({
model : Todo,
localStorage: new Backbone.LocalStorage("todos-backbone"),
done: function() {
return this.where({done: true});
},
remaining: function() {
return this.without.apply(this, this.done());
},
nextOrder: function() {
if (!this.length) return 1;
return this.last().get('order') + 1;
},
comparator: 'order'
});
var TodoView = Backbone.View.extend({
tagName: "li",
template: _.template($('#item-template').html()),
events: {
"click a.destroy" : "clear"
},
initialize: function() {
this.listenTo(this.model, 'destroy', this.remove);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
clear: function(){
this.model.destroy();
}
});
var AppView = Backbone.View.extend({
el: $("#todoapp"),
statsTemplate: _.template($('#stats-template').html()),
events: {
"keypress #new-todo": "createOnEnter",
"click #remove-all": "clearCompleted"
},
initialize: function() {
this.input = this.$("#new-todo");
this.main = $('#main');
this.footer = this.$('footer');
this.listenTo(Todos, 'add', this.addOne);
this.listenTo(Todos, 'all', this.render);
Todos.fetch();
},
render: function() {
var done = Todos.done().length;
var remaining = Todos.remaining().length;
if (Todos.length) {
this.main.show();
this.footer.show();
this.footer.html(this.statsTemplate({done: done, remaining: remaining}));
} else {
this.main.hide();
this.footer.hide();
}
},
createOnEnter: function(e){
if(e.keyCode != 13) return;
if (!this.input.val()) return;
Todos.create({
title: this.input.val()
})
this.input.val('');
},
addOne: function(todo){
var view = new TodoView({model: todo});
this.$("#todo-list").append(view.render().el);
},
clearCompleted: function(){
_.invoke(Todos, 'destroy');
return false;
}
});
for this answer I assume Todos is an instance of TodoList. I also assume that your error is fired by this function in your AppView
clearCompleted: function(){
_.invoke(Todos, 'destroy');
return false;
}
In there you're trying to treat your Backbone.js Collection instance like what it is, a collection eg a list. But Backbone collections are not simply lists, they are objects that have the property models which is a list that contains all your models. So trying to use underscore's invoke (which works on lists) on an object is bound to cause errors.
But don't worry, Backbone neatly implements many Underscore methods for its Model and Collection, including invoke. This means you can invoke destroy for each model in a collection like this
SomeCollection.invoke('destroy');
Hope this helps!

Checkbox still unchecked after triggering the event

I have the following views:
window.DmnView = Backbone.View.extend({
template: _.template($("#tmpl_dmnListItem").html()),
events: {
"click .getWhois": "showWhois",
"click .getDomain": "toBasket"
},
initialize: function() {
this.model.bind('change', this.render, this);
this.model.bind('destroy', this.remove, this);
this.bind('toBasket', dmnListApp.toBasket, this);
},
render: function() {
return $(this.el)
.attr("class", this.model.get("free") ? "dmnItem green" : this.model.get("checked") ? "dmnItem red" : "dmnItem red loader")
.html(this.template(this.model.toJSON()));
},
remove: function() {
$(this.el).remove();
},
showWhois: function() {
showBoxes(this.model.get("info"));
return false;
},
toBasket: function() {
this.model.toBasket();
this.trigger('toBasket');
}
});
window.DmnListApp = Backbone.View.extend({
el: $("#regWrap"),
events: {
"keypress #dmnName": "checkAll"
},
initialize: function() {
this.input = this.$("#dmnName");
this.list = this.$("#dmnList");
this.basket = this.$("#dmnBasket");
dmnList.bind('add', this.addOne, this);
dmnList.bind('all', this.render, this);
},
render: function() {
},
addOne: function(dmnItem) {
var view = new DmnView({model : dmnItem});
this.list.append(view.render());
},
checkOne: function(name, zone, price, days) {
dmnList.create({name: name, zone: zone, price: price, days: days});
},
checkAll: function(e) {
var name = this.input.val();
if (!name || e.keyCode != 13) return;
if (name == "")
name = "yandex";
dmnList.destroyAll();
var zoneList = dmnList.domainsInfo.Name;
var costList = dmnList.domainsInfo.CostOrder;
var daysList = dmnList.domainsInfo.DaysToProlong;
var parent = this;
$.each(zoneList, function(key, zone) {
parent.checkOne(name, zone, costList[key], daysList[key]);
});
this.input.val("");
},
toBasket: function(){
if (this.model.get("inBasket")){
dmnListApp.basket.append($(this.el));
}else{
dmnListApp.list.append($(this.el));
}
}
});
And I have the following template for DmnItem View:
<script id="tmpl_dmnListItem" type="text/template">
<%= checked&&free ? "<input type='checkbox' class='getDomain' />" : ""%><%= name %>.<%= zone %> <%= (free || !checked ) ? (checked) ? '<p class="fr">'+price+" руб./"+days+'</p>' : "" : "<a href='#' class='getWhois fr'>WhoIs</a>" %>
</script>
DmnView listen for clicking on element with the "getDomain" class. This element is the checkbox. I click on this checkbox. And after calling toBasket() method in both Views I see still unchecked checkbox. Why it happened so?
The bug was in rendering. After setting new value to model's attribute render function of view was called and "redraw" the checkbox (so, it's maybe a bug of backbone - after re-Rendering, state of checkbox don't saved). So I added a short line to template, which add "checked" attribute for checkbox if necessary.
Maybe something is wrong in function toBasket (or other). Script can stop before reach end of your handler.

How to bind elements in backbone?

I have a small backbone class:
view = Backbone.View.extend({
events: {
"click textarea" : "doSomething"
},
doSomething : function() {
var textarea = $(this.el).find('textarea')
// I would like to just call, this.textarea, or this.elements.textarea
}
});
Ideally I would like to be able to access my textarea through a variable instead of having to search the element every time. Anyone have any idea on how to accomplish this?
maybe i am under thinking it but how bout giving the textarea a class or id and target specifically when needed,
or create a sub view that generates the textarea
var View = Backbone.View.extend({
el: '#main',
initialize: function(){
this.render();
},
render: function() {
var subview = new SubView();
this.$('form').append(subview.el);
this.$('form').show();
},
});
var SubView = Backbone.View.extend({
tagName: 'textarea',
id: 'whateverId',
events: {
"click" : "doSomething"
},
initialize: function(){
this.render();
},
doSomething : function(event) {
var textarea = $(event.target);
// or var textarea = $(this.el);
},
render: function(){
return $(this.el);
}
});
The other answers get you the reference that you need, but if you really need a handle to the textarea, then you can do something like this:
view = Backbone.View.extend({
initialize: function() {
this.myTextareaElement = $(this.el).find('textarea')
}
events: {
"click textarea" : "doSomething"
},
doSomething : function() {
// use this.myTextareaElement ...
}
});
pass the event as the argument and then use the event target
view = Backbone.View.extend({
events: {
"click textarea" : "doSomething"
},
doSomething : function(event) {
var textarea = $(event.target);
}
});

Resources