Switch between two different templates in backbone.js

I have two different templates for my models. Each time the models are retrieved from the database, the first 3 models (# 1, 2, 3) extracted from the backend will have a view created using the first template, the next 4 models (# 4, 5, 6, 7) will be use the second template, the next 3 models (# 8, 9, 10) will use the first template, etc.

Problem: How can I introduce this striped pattern using backbone.js?

JS code

// Views PhotoListView = Backbone.View.extend({ el: '#photo_list', render: function() { $(this.el).html(''); _.each(this.model.models, function(photo) { $(this.el).append(new PhotoListItemView({ model: photo }).render().el); }, this); return this; } }); PhotoListItemView = Backbone.View.extend({ tagNAme: 'div', className: 'photo_box', template: _.template( $('#tpl_PhotoListView').html() ), initialize: function() { this.model.bind('destroy', this.close, this); }, render: function() { $(this.el).html( this.template( this.model.toJSON() ) ); return this; }, close: function() { this.unbind(); this.remove(); } }); 
+6
source share
1 answer

First of all, your PhotoListView is the packaging of the collection, so you should use this.collection inside the view and new PhotoListView({ collection: c }) to create it. Views view the collection parameter in the same way as they relate to model :

constructor / initialization new View([options])

[...] There are several special options that, if passed, will be attached directly to the view: model , collection , el , id , className , tagName and attributes.

Using the correct names will help prevent confusion. In addition, there are several Underscore methods in the views that you can add this.collection.each(...) instead of _.each(this.collection.models, ...) or _(this.collection.models).each(...) . You can also use this.$el instead of $(this.el) .

And now to your real problem. You can add two templates to the view for each model:

 PhotoListItemView = Backbone.View.extend({ template0: _.template($('#the-first-template-id').html()), template1: _.template($('#the-other-template-id').html()), //... }); 

and the ability to specify which one to use:

 initialize: function(options) { this.template = this['template' + options.template_number]; //... } 

Then you just need to specify the group option from the collection view. An underscore each passes the iteration index of the callback function as the second argument, so you only need a little integer math to figure out which template_number use:

 this.collection.each(function(photo, i) { // Grouped in threes and you're alternating between two templates. var n = Math.floor(i / 3) % 2; var v = new PhotoListItemView({ model: photo, template_number: n }); this.$el.append(v.render().el); }, this); 
+20
source

Source: https://habr.com/ru/post/919702/


All Articles