Reputation: 8682
I have 2 backbone views:
I have multiple types of videos on my site, and some have different behaviour based on their data
attributes (i.e. data-has-overlay
, data-is-expanded
);
I want to initialise them all on VideoView which would then inspect the element passed to it and delegate to a child view if appropriate.
Questions:
Example BB code:
var VideoView = Backbone.View.extends({
initialize: function ( options ) {
// something here to check the el and create ExpandedVideoView if appropriate
if ( this.$el.data('is-expanded') ) {
// Create ExpandedVideoView instead..?
}
},
foo: function () { return 'foo'; }
});
var ExpandedVideoView = VideoView.extends({
initialize: function () {},
bar: function () { return 'bar'; }
});
And the markup looks something like the following:
<div class="Video" data-src="..." data-is-expanded data-has-controls>...</div>
<div class="Video" data-src="..." data-has-controls>...</div>
<div class="Video" data-src="..." data-is-expanded>...</div>
Videos are created in a function similar to the following:
self.$el.find('.Video').each(function ( index, el ) {
self.videoViews.push( new VideoView({ el: el }) );
});
(where self
is a parent view that manages its subviews)
Upvotes: 2
Views: 78
Reputation: 1781
Is there anything built-in to Backbone.js to facilitate this?
In short no. But if you're looking to generate a 'list view' type of view which formats it's items differently based on the type then you could look at Backbone.Marionette's CollectionView and draw some inspiration from that.
Marionette's collection view doesn't support rendering different child views out of the box but you can override a method in the base class to do this with ease.
If you want and need more sophisticated view structures it's definitely worth having a look at Marionette.
Upvotes: 2