I'm working with backbone, this is the static data I have:
var emailfields = new EmailFields([
new EmailField({ id: "data-email", name: "Email" }),
new EmailField({ id: "data-first-name", name: "First Name" }),
new EmailField({ id: "data-last-name", name: "Last Name" }),
]);
I want to create n (n > 1) drop-down lists populated with the same data (emailfields). If any of the values is selected I want to notify the user that he cannot select the same field again.
This is my view:
EmailFieldSelectView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, "addSingleEmailField", "add");
this.add();
},
addSingleEmailField: function(emailfield) {
$("select").each(function() {
$(this).append(new EmailFieldView({ model: emailfield}).render().el);
});
},
add: function() {
this.collection.each(this.addSingleEmailField);
},
});
This is my initialization:
window.emailview = new EmailFieldSelectView({
collection: emailfields
});
In order to populate each select with the same data I'm using $("select").
Is there a better way to do that (I feel this looks like a hack)?
Thanks.
What you've got seems like a reasonable way to approach things. You could use a template to reduce the javascript and need for a view to create select list options.
<script type="text/template" id="exampleTemplate">
<select id="list1">
<% _(emailFields).each(function(emailField) { %>
<option value="<%= emailField.id %>"><%= emailField.name %></option>
<% }); %>
</select>
<select id="list2">
<% _(emailFields).each(function(emailField) { %>
<option value="<%= emailField.id %>"><%= emailField.name %></option>
<% }); %>
</select>
etc.
</script>
Then the view becomes -
EmailFieldSelectView = Backbone.View.extend({
template: _template($('#exampleTemplate').html());
initialize: function() {
_.bindAll(this, "addSingleEmailField", "add");
this.render();
},
render: function() {
this.$el.html(this.template({ emailFields: this.collection.toJSON() }));
return this;
}
});
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.