I have a collection which is rendered by a Backbone Marionette item view. The view is being re-rendered whenever the collection is reset. As far as I can work out, that is default Backbone.Marionette behaviour. Is there a way I can disable it?
var ActiveWordView = M.ItemView.extend({
template: '#active-word-template',
tagName: 'form',
onRender: function() {
// This is being triggered when the collection resets, even
// though I didn't specify that behaviour in an initializer.
console.log("Active word re-rendered");
}
});
var activeWordView = new ActiveWordView({
collection: this.model.get('words'),
});
this.activeWordRegion.show(activeWordView);
Override the initialEvents method.
var ActiveWordView = M.ItemView.extend({
template: '#active-word-template',
tagName: 'form',
initialEvents: function() {},
});
Related
I am having issues with DOM elements being left in memory after being deleted. I have set-up an example shown below. Note I am using the backbone layout manager plugin to manage my views (as well as jQuery).
I have done a heap snapshot in Chrome before and after deleting one of the items in the list and compared the two:
As you can see the LI element is still in memory.
Backbone Layout Manager does call view.unbind() and view.stopListening() when a view is removed.
Below is the example code.
ListOfViewsToDelete.js
var TestModel = Backbone.Model.extend({
});
var TestCollection = Backbone.Collection.extend({
model: TestModel,
});
var ViewToDelete = Backbone.View.extend({
template: "ViewToDelete",
tagName: "li",
events: {
"click .delete-button": "deleteItem"
},
deleteItem: function() {
this.$el.trigger('remove-item', [this.model.id]);
}
});
var ListOfViewsToDelete = Backbone.View.extend({
template: "ListOfViewsToDelete",
initialize: function() {
this.collection = new TestCollection();
for (var i = 0; i < 5; i++) {
this.collection.add(new TestModel({id: i}));
}
this.listenTo(this.collection, 'all', this.render);
},
events: {
"remove-item": "removeItemFromCollection"
},
beforeRender: function() {
this.collection.each(function(testModel) {
this.insertView("ul", new ViewToDelete({
model: testModel
}));
}, this);
},
removeItemFromCollection: function(event, model) {
this.collection.remove(model);
}
});
router.js
app.useLayout("MainLayout").setViews({
"#main": new ListOfViewsToDelete()
}).render();
ListOfViewsToDelete.html
<ul>
</ul>
ViewToDelete.html
View to delete
<button class="delete-button">x</button>
There are several problems with your code:
You use this.$el as model to trigger the remove-item event. You should use your model instead.
The view should wait for events from the model to know when to remove itself.
Here's the code I come up with. If it doesn't work, post your code somewhere so I can run it myself.
var ViewToDelete = Backbone.View.extend({
template: "ViewToDelete",
tagName: "li",
events: {
"click .delete-button": "deleteItem"
},
initialize: function () {
this.listenTo(this.model, 'remove', this.remove);
},
deleteItem: function() {
this.model.remove();
}
});
The default implementation of view.remove() will remove this.$el and stop listening to the model:
remove: function() {
this.$el.remove();
this.stopListening();
return this;
},
EDIT: Thank you for posting your code online. Here's what I think is happening (I'm also documenting for future viewers).
If you take a snapshot, filter on Detached DOM Tree, you see:
The important part is the retaining tree: references that prevent the LI from being deleted. The only significant thing is sizzle-1364380997635. It doesn't come from your code, it actually comes from jQuery, more specifically from its Sizzle engine. The key comes from here:
https://github.com/jquery/sizzle/blob/master/sizzle.js#L33
If you look further in the code, you see that there's a cache:
https://github.com/jquery/sizzle/blob/master/sizzle.js#L1802
So, in a nutshell, you code does not leak, but jQuery has an internal cache that prevents it from being removed anyway. This cache can only contain a few dozen elements, so it won't retain elements forever.
I'm semi-new to backbone. I'm trying to bind a collection to a view so that when a new model is added to a collection, the view is updated. I think when you do this with models you can bind to the model's change event. But how do you do the same with collections?
App.Views.Hotels = Backbone.View.extend({
tagName: 'ul',
render: function() {
this.collection.each(this.addOne, this);
var floorplanView = new App.Views.Floorplans({collection:floorplanCollection});
$('.floorplans').html(floorplanView.render().el);
return this;
},
events: {'click': 'addfloorplan'},
addOne: function(hotel) {
var hotelView = new App.Views.Hotel ({model:hotel});
this.$el.append(hotelView.render().el);
},
addfloorplan: function() {
floorplanCollection.add({"name": "another floorplan"});
}
});
App.Collections.Floorplans = Backbone.Collection.extend({
model: App.Models.Floorplan,
initialize: function () {
this.bind( "add", function() {console.log("added");} );
}
});
The click event fires and adds to the collection. But how do I get it to update the view?
You can listen to the collection's add event, which fires when a new item is added to the collection. In modern versions of Backbone, the method listenTo is preferred to bind or on for listening to events. (Read de documentation for more info)
For example, in your case this should do the trick:
App.Views.Hotels = Backbone.View.extend({
initialize: function() {
this.listenTo(this.collection,'add', this.addOne);
},
//rest of code
Hope this helps!
Here is a nice tutorial I had followed long ago.
An Intro to Backbone.js: Part 3 – Binding a Collection to a View
It helps you define a DonutCollectionView that will, when given a collection of donuts, render an UpdatingDonutView for each donut.
I'm learning Backbone.js for the first time and I'm having an issue trying to get a custom event from triggering (or from the View from recognising when it's been triggered)?
You can see my Collection code here: https://github.com/Integralist/Backbone-Playground/blob/master/Assets/Scripts/App/main.js#L72-86 which when initialized it triggers a custom collection:init event.
var Contacts = Backbone.Collection.extend({
model: Contact,
initialize: function(){
this.trigger('collection:init');
this.bind('add', this.model_added, this);
},
model_added: function(){
console.log('A new model has been created so trigger an event for the View to update the <select> menu');
}
});
But later on in my View where I'm listening for that event I can't get the function populate to fire: https://github.com/Integralist/Backbone-Playground/blob/master/Assets/Scripts/App/main.js#L90-107
var ContactsView = Backbone.View.extend({
initialize: function(){
console.log(contacts.models, 'get initial model data and populate the select menu?');
},
events: {
'collection:init': 'populate',
'change select': 'displaySelected'
},
populate: function(){
console.log('populate the <select> with initial Model data');
},
displaySelected: function (event) {
console.log('get model data and display selected user', event);
}
});
Any ideas what I'm doing wrong?
The events hash in a view is used to bind events from the DOM to your view, e.g. events raised by the elements in your rendered view. To listen to events raised by your collection, you will have to set them manually:
var ContactsView = Backbone.View.extend({
initialize: function(){
contacts.on("collection:init",this.populate,this);
}
...
});
Note that you are using a global contacts variable, I would advise to use Backbone mechanisms and pass your collection to the constructor, as you do with the el:
var ContactsView = Backbone.View.extend({
initialize: function(){
console.log(this.collection.models);
this.collection.on("collection:init",this.populate,this);
}
...
});
var contacts_view = new ContactsView({
el: $('#view-contacts'),
collection:contacts
});
As #mu said in the comments, as is, your event won't do anything since you trigger it in the initialize method of the collection, which is automatically called by the constructor of the collection therefore before you can bind anything in the view. See this Fiddle to visualize the call order : http://jsfiddle.net/yRuCN/
Trigger it elsewhere, or, if I read correctly your intent, you (probably) want to use the built in reset event:
var ContactsView = Backbone.View.extend({
initialize: function(){
this.collection.on("reset",this.populate,this);
}
...
});
See http://jsfiddle.net/yRuCN/1/ for an example with potential uses.
My Backbone.js app has a popup editor view that will be repeatedly closed and reopened as the user makes changes. I'm trying to figure out the cleanest way to implement this, and I'm stuck on an event delegation issue.
I believe the problem lies in the way I'm applying the template in my render method. I haven't had any issues with getting events to fire in other views, but those views differed in that they had a model. The view I'm having issues with is more of an application view that contains sub-views, so I'm not sure how to pass the view's context to the MyApp view.
Here's my code:
MyApp = Backbone.View.extend({
tagName: 'div',
template: _.template($('#app-template').html()),
initialize: function() {
_.bindAll(this);
this.render();
},
render: function() {
$('#container').html(this.template);
return this;
},
events: {
"click .save" : "onSaveClicked"
},
onSaveClicked: function () {
console.log("Save clicked.");
this.$el.remove();
}
});
$('#show').click(function () {
var myapp = new MyApp;
});
I've also posted it as a jsFiddle.
I stepped through the Backbone.js source, and it appears that render is called first, then events are assigned, which is what I'd expect. Everything looks OK from what I can tell, but onSaveClicked never fires when I click Save.
The desired functionality is that clicking Show displays the form and Save removes it. If there's a better way to do this that's more inline with Backbone's underlying philosophy I'm open to that as well. You'll notice that I'm nesting an unnamed div inside container, and that's because I wanted to maintain a consistent anchor point for my popup.
The events are bound to the view el, but you never append the el to the DOM. Try
MyApp = Backbone.View.extend({
tagName: 'div',
template: _.template($('#app-template').html()),
initialize: function() {
_.bindAll(this);
this.render();
},
render: function() {
this.$el.html(this.template);
return this;
},
events: {
"click .save" : "onSaveClicked"
},
onSaveClicked: function () {
console.log("Save clicked.");
this.$el.remove();
}
});
$('#show').click(function () {
var myapp = new MyApp;
$("#container").append(myapp.$el);
});
http://jsfiddle.net/WBPqk/18/
Note that in your Fiddle you bound the click event to .save where your template uses a done class.
So I have a View that looks like this.
//base class
var SelectListView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'addOne', 'addAll');
this.collection.bind('reset', this.addAll);
},
addAll: function() {
this.collection.each(this.addOne);
},
events: {
"change": "changedSelected"
},
changedSelected: function() {
this.selected = $(this.el);
this.setSelectedId($(this.el).val());
}
});
//my extended view
var PricingSelectListView = SelectListView.extend({
addOne: function(item) {
$(this.el).append(new PricingView({ model: item }).render().el);
}
});
I have instantiated the view like this...
var products = new ProductPricings();
var pricingsView = new PricingSelectListView({
el: $("#sel-product"),
collection: products
});
Somewhere else (another views custom method)I have updated the pricing view's collection
pricingsView.collection = new ProductPricings(filtered);
This does not seen to do anything.
pricingsView.render();
So now the collection has fewer items but the new view is never rendered or refreshed in the DOM.
How to I do I 1.) refresh the rendering in the DOM? 2.) Make it automatically refresh the DOM? Do I have to somehow tell it to render when ever the collection changes?
You bound addOne() to a reset event. When you just replace the pricingsView.collection instance then that event is not triggered and addOne() is not executed.
Try instead:
pricingsView.collection.reset(filtered);
This might work since you bind to collection's reset event already:
pricingsView.collection.reset(filtered);
http://backbonejs.org/#Collection-reset
You still have tweak your rendering logic to remove old markup from the view when reset happens.