I am trying to build a simple contact editor application in Backbone.js and I have run into a bit of an issue that I don't know how to solve because I'm not familiar with Backbone.js yet.
I have a Model Contact
and that item has a field ProductLineID
(each Contact has a Product Line that it is associated with). In displaying the editor for this Contact I would like to display a dropdown list with the possible ProductLine options and have it preset to the current value. How would I do that in Backbone.js?
I know how to do it 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.
That would accomplish precisely what I want, but I don't know how to do the equivalent in Backbone.js.
I can provide more code from my actual example, but this seems like it's a bit of a trivial example and does not require specific code.
Something like the following would work if you used the 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 would just have to make sure that you passed in the productLineOptions
object into the template's context.
Backbone.js does not do databinding out of the box, like Knockout does. It leaves that aspect up to the developer to do however they wish. The basic way is to set up event listeners for changes.
If you do want to do knockout-style databinding, there's a project which may support what you need.
https://github.com/derickbailey/backbone.modelbinding
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With