How can I display a select list (drop-down list) for a model property in BackboneJS?

I am trying to create a simple contact editor application in Backbone.js and I have encountered a problem that I don’t know how to solve, because I am not familiar with Backbone.js yet.

I have a Model Contact , and this element has a ProductLineID field (each contact has a Product Line with which it is associated). When displaying an editor for this contact, I would like to display a drop-down list with possible ProductLine parameters and set it to the current value. How can I do this in Backbone.js?

I know how to do this in knockout.js with data binding:

 <select id="ProductLineID" name="ProductLineID" data-bind="options: productLineOptions, optionsValue: 'ID', optionsText: 'Name', value: ProductLineID, optionsCaption: 'All'"> </select> 

In this example, productLineOptions is a JSON object that is already preloaded on the page.

This will do exactly what I want, but I don’t know how to make the equivalent in Backbone.js.

I can provide more code from my actual example, but it looks like this is a slightly trivial example and does not require specific code.

+7
source share
2 answers

Something like the following will work if you used underscore templates :

 <select id="ProductLineID" name="ProductLineID"> <option value="">--select a product line--</option> <% _(productLineOptions).each(function(pl) { %> <option value="<%= pl.ID %>"><%= pl.Name %></option> <% }); %> </select> 

And then you just need to make sure that you pass the productLineOptions object to the template context.

+13
source

Backbone.js does not collect data out of the box, as Knockout does. He leaves this aspect to the developer, although they want it. The main way is to configure event listeners for changes.

If you want to bind data to a knockout, there is a project that can support what you need.

https://github.com/derickbailey/backbone.modelbinding

+4
source

All Articles