Backbone inheritance can't access child method in child - backbone.js

I'm currently working with backbone.js and I have a strange problem :
I have a class :
var AppView = Backbone.View.extend({
...
events: {
// Score bar
"mouseover #jauge-bottom": "showToolTip",
"mouseleave #jauge-bottom": "hideToolTip",
// Form events and inputs
"click a.social": "socialAction",
"click a#sound": "switchMute",
"submit form#form-intro": "introForm",
"click .choisir-perso a.btn-jouer": "sexSet",
"mouseover .overlay": "sexHover",
"click #male": "sexClick",
"mouseover #male": "sexHover",
"click #female": "sexClick",
"mouseover #female": "sexHover",
"mouseleave #male": "sexHover",
"mouseleave #female": "sexHover",
"click input.field": "inputFocus",
"blur input.field": "inputFocus"
},
initialize: function() {
this.user.bind('change', this.setScore, this);
_.bindAll(this, 'render', 'setScore');
},
And a subclass :
var Level1 = AppView.extend({
events: _.extend({
}, appMainView.prototype.events), // set the inheritance events
render: function(){
this.bla();
},
bla: function(){
console.log('bla');
}
});
I obtain this error in my console :
this.bla is not a function
My question is why and how can I fix it ?

You're receiving the error because the render function context is not set to the view.
Add an initialize function to bind the render function to the view.
var Level1 = AppView.extend({
initialize: function() {
_.bindAll(this, 'render');
},
events: _.extend({
}, appMainView.prototype.events), // set the inheritance events
render: function(){
this.bla();
},
bla: function(){
console.log('bla');
}
});

Related

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

Backbone.js auto render view after destroy

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

Backbone render after cancelling

I have the following backbone view. I had a doubt. In case if a model is deleted, i call the render after cancel(First Approach), the other way of doing it would be to have an initialize function, which renders the model listening to the event changes, inside the views.(Second Approach)
Could someone please let me know, the difference between one and two. As to which of the two is better.
First Approach
var AppointmentView = Backbone.View.extend({
template: _.template('">' +
'<%= title %>' +
'x'),
events: { "click a": "cancel" },
cancel: function(){
this.model.cancel();
this.render(); // rendering after cancel
},
render: function(){
this.$el.html(this.template(this.model.toJSON()));
}
});
Second Approach
var AppointmentView = Backbone.View.extend({
template: _.template('<span class="<% if(cancelled) print("cancelled") %>">' +
'<%= title %></span>' +
'x'),
initialize: function(){
this.model.on("change", this.render, this);
},
events: { "click a": "cancel" },
cancel: function(){
this.model.cancel();
},
render: function(){
this.$el.html(this.template(this.model.toJSON()));
}
});
I would define a custom cancelled event, trigger that from your cancel method, and bind to that event in the view.
var Appointment = Backbone.Model.extend({
cancel: function() {
//cancellation code...
this.trigger('cancelled', this);
}
});
var AppointmentView = Backbone.Model.extend({
initialize: function() {
this.listenTo(this.model, 'cancelled', this.render);
}
});
This way your view will re-render, even if the model is cancelled from elsewhere than the view itself, but you still get the specific behavior or only re-rendering upon cancel, and not on every change.

Call method in collection, when View's method called

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.

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