There is an address view which renders a form with the basic address fields including zip code textbox and city/suburb dropdown. Ideally when the user types in the the zip code, the city dropdown should automatically populate with values (cities/suburbs) under that zip code. I know someone already raised a question about cascading dropdowns however this is different in a way that I want the values of the cities/suburbs should be taken as a result by calling an HTTP Get request.
How do I implement it using backbone.js? I have done something but i feel that it is somehow wrong. What I did is I added a function that will populate a "suburbs" collection and return the collection as a parameter in calling a macro that will update the dropdown. Codes below.
code snippets from Address.Model.js
...
, updateCities:function(){
var suburb = Backbone.Model.extend({
});
var SuburbCollection = Backbone.Collection.extend({
model: suburb,
url:"http link to get the suburbs list"
});
var SubCol = new SuburbCollection();
SubCol.fetch();
return SubCol;
}
...
Code snippets from citiesDropdown macro
<% registerMacro('citiesDropdown', function (options) { %>
<%
var suburbs= options.cities;
%>
<label class="control-label" for="<%= options.manage ? options.manage : ''%>state">
<%= _('City').translate() %>
<small><%= _('(required)').translate() %></small>
</label>
<div class="controls">
<select class="input-xlarge" id="<%= options.manage ? options.manage : ''%>city" name="city" data-type="city">
<option value="">
<%= _('-- Select --').translate() %>
</option>
<% _.each(suburbs, function (suburb) { %>
<option>
<%= suburb.name %>
</option>
<% }) %>
</select>
</div>
<% }) %>
Address.View
...
, events: {
...
,'blur input[data-type="zip"]': 'updateCity'
...
, updateCity: function (e)
{
this.$('[data-type="city"]').closest('.control-group').empty().append(
SC.macros.citiesDropdown({
cities: this.model.updateCities()
})
);
}
....