Rendering each collection item asynchronously in Backbone.js - backbone.js

I am trying to render a collection of items. Normally what I would do is something like this:
StuffView = Backbone.View.extend({
...
render: function(){
...
this.$el.html( ... );
return this;
}
...
});
StuffCollectionView = Backbone.View.extend({
...
render: function(){
this.collection.each(addOne, this);
},
addOne: function(stuff){
var view = new StuffView({model: stuff});
this.$el.append(view.render().el);
}
...
});
However, this time I'm building a bit different type of view. Each StuffView's rendering takes some time, so I can't do this synchronously. The code for the new StuffView looks something like this:
StuffView = Backbone.View.extend({
...
render: function(){
...
// Asynchronous rendering
SlowRenderingFunction(function(renderedResult){
this.$el.html(renderedResult);
});
}
});
In this case, I can't just return this from render and append its result to the StuffCollectionView's el. One hack I thought of was to pass a callback function to StuffView's render, and let it callback when it has finished rendering. Here's an example:
StuffView = Backbone.View.extend({
...
render: function(callback){
...
// Asynchronous rendering
SlowRenderingFunction(function(renderedResult){
this.$el.html(renderedResult);
callback(this);
});
}
});
StuffCollectionView = Backbone.View.extend({
...
initialize: function(){
_.bindAll(this, "onStuffFinishedRendering");
},
render: function(){
this.collection.each(addOne, this);
},
addOne: function(stuff){
var view = new StuffView({model: stuff});
view.render(onStuffFinishedRendering);
},
onStuffFinishedRendering: function(renderedResult){
this.$el.append(renderedResult.el);
}
...
});
But it's not working for some reason. Furthermore, this feels too hacky and doesn't feel right. Is there a conventional way to render children views asynchronously?

Can't you pass StuffCollectionView's el into the SlowRenderingFunction? It's a bit nasty but I don't see why it wouldn't work.
Edit: I should say, and make SlowRenderingFunction an actual property of StuffView, so that StuffViewCollection can call it instead of calling render.

You can try using _.defer to prevent the collection items rendering blocking the UI.
Refer http://underscorejs.org/#defer for more details.
StuffCollectionView = Backbone.View.extend({
...
render: function(){
var self = this;
_(function() {
self.collection.each(addOne, self);
}).defer();
}
...
});

Related

A proper example of backbone views: Change attributes, CRUD, without Zombie Views

Trying to make a reasonable teaching model of Backbone that shows proper ways to take advantage of backbone's features, with a grandparent, parent, and child views, models and collections...
I am trying to change a boolean attribute on a model, that can be instantiated across multiple parent views. How do I adjust the listers to accomplish this?
The current problem is that when you click on any non-last child view, it moves that child to the end AND re-instantiates it.
Plnkr
Click 'Add a representation'
Click 'Add a beat' (you can click this more than once)
Clicking any beat view other than the last one instantiates more views of the same beat
Child :
// our beat, which contains everything Backbone relating to the 'beat'
define("beat", ["jquery", "underscore", "backbone"], function($, _, Backbone) {
var beat = {};
//The model for our beat
beat.Model = Backbone.Model.extend({
defaults: {
selected: true
},
initialize: function(boolean){
if(boolean) {
this.selected = boolean;
}
}
});
//The collection of beats for our measure
beat.Collection = Backbone.Collection.extend({
model: beat.Model,
initialize: function(){
this.add([{selected: true}])
}
});
//A view for our representation
beat.View = Backbone.View.extend({
events: {
'click .beat' : 'toggleBeatModel'
},
initialize: function(options) {
if(options.model){
this.model=options.model;
this.container = options.container;
this.idAttr = options.idAttr;
}
this.model.on('change', this.render, this);
this.render();
},
render: function(){
// set the id on the empty div that currently exists
this.$el.attr('id', this.idAttr);
//This compiles the template
this.template = _.template($('#beat-template').html());
this.$el.html(this.template());
//This appends it to the DOM
$('#'+this.container).append(this.el);
return this;
},
toggleBeatModel: function() {
this.model.set('selected', !this.model.get('selected'));
this.trigger('beat:toggle');
}
});
return beat;
});
Parent :
// our representation, which contains everything Backbone relating to the 'representation'
define("representation", ["jquery", "underscore", "backbone", "beat"], function($, _, Backbone, Beat) {
var representation = {};
//The model for our representation
representation.Model = Backbone.Model.extend({
initialize: function(options) {
this.idAttr = options.idAttr;
this.type = options.type;
this.beatsCollection = options.beatsCollection;
//Not sure why we have to directly access the numOfBeats by .attributes, but w/e
}
});
//The collection for our representations
representation.Collection = Backbone.Collection.extend({
model: representation.Model,
initialize: function(){
}
});
//A view for our representation
representation.View = Backbone.View.extend({
events: {
'click .remove-representation' : 'removeRepresentation',
'click .toggle-representation' : 'toggleRepType',
'click .add-beat' : 'addBeat',
'click .remove-beat' : 'removeBeat'
},
initialize: function(options) {
if(options.model){this.model=options.model;}
// Dont use change per http://stackoverflow.com/questions/24811524/listen-to-a-collection-add-change-as-a-model-attribute-of-a-view#24811700
this.listenTo(this.model.beatsCollection, 'add remove reset', this.render);
this.listenTo(this.model, 'change', this.render);
},
render: function(){
// this.$el is a shortcut provided by Backbone to get the jQuery selector HTML object of this.el
// so this.$el === $(this.el)
// set the id on the empty div that currently exists
this.$el.attr('id', this.idAttr);
//This compiles the template
this.template = _.template($('#representation-template').html());
this.$el.html(this.template());
//This appends it to the DOM
$('#measure-rep-container').append(this.el);
_.each(this.model.beatsCollection.models, function(beat, index){
var beatView = new Beat.View({container:'beat-container-'+this.model.idAttr, model:beat, idAttr:this.model.idAttr+'-'+index });
}, this);
return this;
},
removeRepresentation: function() {
console.log("Removing " + this.idAttr);
this.model.destroy();
this.remove();
},
//remove: function() {
// this.$el.remove();
//},
toggleRepType: function() {
console.log('Toggling ' + this.idAttr + ' type from ' + this.model.get('type'));
this.model.set('type', (this.model.get('type') == 'line' ? 'circle' : 'line'));
console.log('Toggled ' + this.idAttr + ' type to ' + this.model.get('type'));
this.trigger('rep:toggle');
},
addBeat: function() {
this.trigger('rep:addbeat');
},
removeBeat: function() {
this.trigger('rep:removebeat');
}
});
return representation;
});
This answer should be working properly for all views, being able to create, or delete views without effecting non related views, and change attributes and have related views auto update. Again, this is to use as a teaching example to show how to properly set up a backbone app without the zombie views...
Problem
The reason you are seeing duplicate views created lies in the render() function for the Beat's view:
render: function(){
// set the id on the empty div that currently exists
this.$el.attr('id', this.idAttr);
//This compiles the template
this.template = _.template($('#beat-template').html());
this.$el.html(this.template());
//This appends it to the DOM
$('#'+this.container).append(this.el);
return this;
}
This function is called when:
when the model associated with the view changes
the beat view is first initialized
The first call is the one causing the problems. initialize() uses an event listener to watch for changes to the model to re-render it when necessary:
initialize: function(options) {
...
this.model.on('change', this.render, this); // case #1 above
this.render(); // case #2 above
...
},
Normally, this is fine, except that render() includes code to push the view into the DOM. That means that every time the model associated with the view changes state, the view not only re-renders, but is duplicated in the DOM.
This seems to cause a whole slew of problems in terms of event listeners being bound incorrectly. The reason, as far as I know, that this phenomenon isn't caused when there is just one beat present is because the representation itself also re-renders and removes the old zombie view. I don't entirely understand this behavior, but it definitely has something to do with the way the representation watches it's beatCollection.
Solution
The fix is quite simple: change where the view appends itself to the DOM. This line in render():
$('#'+this.container).append(this.el);
should be moved to initialize, like so:
initialize: function(options) {
if(options.model){
this.model=options.model;
this.container = options.container;
this.idAttr = options.idAttr;
}
this.model.on('change', this.render, this);
this.render();
$('#'+this.container).append(this.el); // add to the DOM after rendering/updating template
},
Plnkr demo with solution applied

Backbone.js .on('add') to Collection is not causing a render

I am following CodeSchool's 'Anatomy of Backbone.js' and cannot get this to work on my machine. There are similar questions, but they have a lot of extra stuff going on and, for someone brand-new like me, it's making it hard to learn.
Here's the code as simple/universal as possible:
var WorldEvent = Backbone.Model.extend({});
var WorldEventView = Backbone.View.extend({
events: {
'click' : 'focusEvent'
},
focusEvent: function(){
alert('great.');
},
className : 'pin bounce',
render : function () {
console.log('did something');
this.$el.html("rendered");
return this;
}
});
var WorldEventCollection = Backbone.Collection.extend({
model: WorldEvent,
url: '/events'
});
var worldEventCollection = new WorldEventCollection();
var worldEventCollectionView = new WorldEventView({
collection: worldEventCollection,
initialize: function(){
this.collection.on('add', this.addOne, this);
this.collection.on('reset', this.addAll, this);
},
addOne: function(myEvent){
var worldEventView = new WorldEventView({ model: myEvent });
this.$el.append(worldEventView.render().el);
},
addAll: function(){
this.collection.forEach(this.addOne, this);
},
render: function(){
this.addAll();
}
});
The good news is that if I call
worldEventCollection.add(new WorldEvent( {<my data>} ));
... the new model is added to worldEventCollection - I've logged worldEventCollection and worldEventCollection.length to verify.
The bad news is that "did something" doesn't appear in the console and I see no evidence of a render.
Please help, I've wasted a ton of time on what is probably super simple. Thank you.
UPDATE
Okay, I found one of my issues. I needed to define a separate WorldEventCollectionView class altogether, so this was NOT correct:
var worldEventCollectionView = new WorldEventView({
collection: worldEventCollection,
...
Instead, I believe one correct approach is:
var WorldEventCollectionView = Backbone.View.extend({
initialize: function(){
this.collection.on('add', this.addOne, this.collection);
...
And then:
var worldEventCollectionView = new WorldEventCollectionView({ collection: worldEventCollection });
WorldEventView.render must end with return this; as per backbone view convention, otherwise chaining such as worldEventView.render().el will not work. Specifically, that will throw an exception since render() returns undefined and you try to access the .el property of undefined.
There's several other things that are not quite right about your snippet as well, but fix that first and see if you can take it from there. Generally in a view's render method, you want to populate HTML inside the view's this.$el and return this; at the end of render and really that's all you should be doing. Render has a very specific purpose and code that isn't following that basic idea and semantic belongs elsewhere.
Oh so this:
var worldEventCollectionView = new WorldEventView({
should be:
var WorldEventCollectionView = Backbone.View.extend({

Event handling between views

Ok I have a layout like the one in this pic:
The table in the upper part of the screen is made by:
MessageListView
define(['backbone','collections/messages','views/message'], function(Backbone, MessageCollection, MessageView) {
var MessageListView = Backbone.View.extend({
el: '#messagesContainer',
initialize: function() {
this.collection = new MessageCollection();
this.collection.fetch({reset:true});
this.listenTo( this.collection, 'reset', this.render );
this.table = this.$el.find("table tbody");
this.render();
},
render: function() {
this.collection.each( function(message, index) {
this.renderMessage(message, index);
}, this);
},
renderMessage: function(message, index) {
var view = new MessageView({
model:message,
className: (index % 2 == 0) ? "even" : "odd"
});
this.table.append( view.render().el );
}
});
return MessageListView;
});
MessageView
define(['backbone','models/message'], function(Backbone, MessageCollection, MessageView) {
var MessageView = Backbone.View.extend({
template: _.template( $("#messageTemplate").html() ),
render: function() {
this.setElement( this.template(this.model.toJSON()) );
return this;
},
events:{
'click':'select'
},
select: function() {
// WHAT TO DO HERE?
}
});
return MessageView;
});
AppView
define(['backbone','views/messages'], function(Backbone, MessageList) {
var App = Backbone.View.extend({
initialize: function() {
new MessageList();
}
});
return App;
});
I will soon add a new view (maybe "PreviewView") in the lower part of the screen.
I want to make something happen inside the "PreviewView" when user clicks a row.
For example, it could be interesting to display other model's attributes (details, e.g.) inside the PreviewView.
What is the best practice?
holding a reference to PreviewView inside each MessageView ?
triggering events inside select method, and listening to them using on() inside the preview view.
using a transient "selected" attribute in my model, and make PreviewView listen to collection "change" events?
Thank you, if you need more details tell me please, I'll edit the question.
Not sure about the best practice but I found this solution trivial to implement. I created a global messaging object, bus, whatever:
window.App = {};
window.App.vent = _.extend({}, Backbone.Events);
You have to register the "triggerable" functions of PreviewView on the previously created event bus (according to your example, this should be in the PreviewView):
initialize: function () {
App.vent.on('PreviewView.show', this.show, this);
}
Now you should be able to trigger any of registered events from anywhere within your application by calling: App.vent.trigger. For example when the user click on a row you will have something similar:
App.vent.trigger('PreviewView.show');
in case if you have to send and object along with the triggered event use:
App.vent.trigger('PreviewView.show', data);

After Render Event on CompositeView with Backbone.Marionette

I have a Marionette CompositeView with a search panel and the collection of result data.
I would like to call a function when:
the search panel is rendered.
the collection is not rendered yet.
this function should not be called when the collection is rendered.
I did it in this way: (but "afterRender" function get called twice)
// VIEW
App.MyComposite.View = Backbone.Marionette.CompositeView.extend({
// TEMPLATE
template: Handlebars.compile(templates.find('#composite-template').html()),
// ITEM VIEW
itemView: App.Item.View,
// ITEM VIEW CONTAINER
itemViewContainer: '#collection-block',
//INITIALIZE
initialize: function() {
this.bindTo(this,'render',this.afterRender);
},
afterRender: function () {
//THIS IS EXECUTED TWICE...
}
});
How can i do this?
==========================EDIT==================================
I solved it in this way, if you have an observation please let me know.
// VIEW
App.MyComposite.View = Backbone.Marionette.CompositeView.extend({
//INITIALIZE
initialize: function() {
//this.bindTo(this,'render',this.afterRender);
this.firstRender = true;
},
onRender: function () {
if (firstRender) {
//DO STUFF HERE..............
this.firstRender = false;
}
}
});
Marionette provides an onRender method built in to all of it's views, so you can get rid of the this.bindTo(this, 'render', this.afterRender) call:
// VIEW
App.MyComposite.View = Backbone.Marionette.CompositeView.extend({
// TEMPLATE
template: Handlebars.compile(templates.find('#composite-template').html()),
// ITEM VIEW
itemView: App.Item.View,
// ITEM VIEW CONTAINER
itemViewContainer: '#collection-block',
//INITIALIZE
initialize: function() {
// this.bindTo(this,'render',this.afterRender); // <-- not needed
},
onRender: function () {
// do stuff after it renders, here
}
});
But to get it to not do the work when the collection is not rendered, you'll have to add logic to the onRender method that checks whether or not the collection was rendered.
This largely depends on what you're trying to do with the rendering when no items are rendered from the collection.
For example... if you want to render a "No Items Found" message, you can use the built in emptyView configuration for the composite view.
NoItemsFoundView = ItemView.extend({
// ...
});
CompositeView.extend({
emptyView: NoItemsFoundView
});
But if you have some special code that needs to be run and do certain things that aren't covered by this option, then you'll have to put in some logic of your own.
CompositeView.extend({
onRender: function(){
if (this.collection && this.collection.length === 0) {
// do stuff here because the collection was not rendered
}
}
});
Just use onShow function
Backbone.Marionette.ItemView.extend({
onShow: function(){
// react to when a view has been shown
}
});
http://marionettejs.com/docs/marionette.view.html#view-onshow

Backbone.js event after view.render() is finished

Does anyone know which event is fired after a view is rendered in backbone.js?
I ran into this post which seems interesting
var myView = Backbone.View.extend({
initialize: function(options) {
_.bindAll(this, 'beforeRender', 'render', 'afterRender');
var _this = this;
this.render = _.wrap(this.render, function(render) {
_this.beforeRender();
render();
_this.afterRender();
return _this;
});
},
beforeRender: function() {
console.log('beforeRender');
},
render: function() {
return this;
},
afterRender: function() {
console.log('afterRender');
}
});
Or you can do the following, which is what Backbone code is supposed to look like (Observer pattern, aka pub/sub). This is the way to go:
var myView = Backbone.View.extend({
initialize: function() {
this.on('render', this.afterRender);
this.render();
},
render: function () {
this.trigger('render');
},
afterRender: function () {
}
});
Edit: this.on('render', 'afterRender'); will not work - because Backbone.Events.on accepts only functions. The .on('event', 'methodName'); magic is made possible by Backbone.View.delegateEvents and as such is only available with DOM events.
As far as I know - none is fired. Render function is empty in source code.
The default implementation of render is a no-op
I would recommend just triggering it manually when necessary.
If you happen to be using Marionette, Marionette adds show and render events on views. See this StackOverflow question for an example.
On a side note, Marionette adds a lot of other useful features that you might be interested in.
I realise this question is fairly old but I wanted a solution that allowed the same custom function to be called after every call to render, so came up with the following...
First, override the default Backbone render function:
var render = Backbone.View.prototype.render;
Backbone.View.prototype.render = function() {
this.customRender();
afterPageRender();
render();
};
The above code calls customRender on the view, then a generic custom function (afterPageRender), then the original Backbone render function.
Then in my views, I replaced all instances of render functions with customRender:
initialize: function() {
this.listenTo(this.model, 'sync', this.render);
this.model.fetch();
},
customRender: function() {
// ... do what you usually do in render()
}
Instead of adding the eventhandler manually to render on intialization you can also add the event to the 'events' section of your view. See http://backbonejs.org/#View-delegateEvents
e.g.
events: {
'render': 'afterRender'
}
afterRender: function(e){
alert("render complete")
},
constructor: function(){
Backbone.View.call(this, arguments);
var oldRender = this.render
this.render = function(){
oldRender.call(this)
// this.model.trigger('xxxxxxxxx')
}
}
like this http://jsfiddle.net/8hQyB/

Resources