Determine If Backbone View Has Rendered
I nice simple way to check whether a Backbone view element is part of the DOM yet or not.
by Adam Boduch
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
JavaScript
var MyView = Backbone.View.extend({
tagName: 'ul',
initialize: function( options ) {
var coll = options.collection;
// Setup event listeners on collection
this.listenTo( coll, 'add', this.onAdd );
this.listenTo( coll, 'remove', this.onRemove );
// Render the view using collection data
coll.forEach( _.bind( function( m ) {
$( '<li/>' )
.attr( 'id', m.cid )
.text( m.cid )
.appendTo( this.$el );
}, this ));
this.$el.appendTo( 'body' );
},
onAdd: function( model, collection ) {
// Don't do anything if the view isn't rendered
if ( !this.rendered() ) {
return;
}
// Add the new item to the DOM
$( '<li/>' )
.attr( 'id', model.cid )
.text( model.cid )
.insertAfter( this.$el.children().get(
collection.indexOf( model ) - 1 ));
},
onRemove: function( model ) {
// Don't do anything if the view isn't rendered
if ( !this.rendered() ) {
return;
}
// Remove the model from the DOM
this.$( '#' + model.cid ).remove();
},
// Returns true if the view element is in the DOM
rendered: function() {
return $.contains( document, this.el );
}
});
$(function() {
var coll = new Backbone.Collection( new Array( 10 ) );
new MyView({ collection: coll});
coll.add( 'foo' );
coll.at( 4 ).destroy();
});