My Backbone has several views containing forms with text inputs, fields, and check boxes. The selection fields should be filled using data from my API. This selection field can be reused in several different forms.
What is the commonly used approach to populate these dropdowns? Here is the solution I put together ... Is there a more general approach?
A reusable field that fills itself ... app / views / shared / location_selection.js:
define([ 'jquery', 'backbone', 'app/views/base', 'app/collections/location' ], function($, Backbone, BaseView, LocationCollection) { 'use strict'; return BaseView.extend({ initialize: function(options) { this.options = options || {}; this.options.id = this.options.id || 'location'; this.options.showBlank = typeof this.options.showBlank != 'undefined' ? this.options.showBlank : false; this.collection = new LocationCollection(); }, render: function() { this.setElement('<select id="' + this.options.id + '"></select>'); var self = this; this.collection.fetch({ success: function() { if (self.options.showBlank) { self.$el.append('<option></option'); } self.collection.each(function(model) { self.$el.append('<option value="' + model.get('id') + '">' + model.get('name') + '</option>'); }); } }); return this; } }); });
And a snippet from another view that uses this view:
render: function() { this.$el.html(this.template(this.model.toJSON())); var locationSelectionView = new LocationSelectionView({ showBlank: !this.model.get('id') }); this.$('.location').append(locationSelectionView.render().el); return this; },
And the form template:
<form role="form"> <div class="form-group"> <label for="imei">IMEI</label> <input type="text" class="form-control" id="imei" value="{{data.imei}}" /> </div> <div class="form-group location"> <label for="location">Location</label> </div> <div class="checkbox"> <label><input id="master" type="checkbox"{{#if master}} checked="checked"{{/if}} /> Master</label> </div> </form>
Chad johnson
source share