简体   繁体   中英

How can I display a select list (dropdown) for a Model property in BackboneJS?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM