I’m trying to do something like the following:
var viewModel = function() {
var self = this;
$.getJSON("/categories", function(data) {
$.each(data, function(index, cat) {
self[cat] = ko.observable(true);
});
});
}
The data coming in is a JSON array of category names – I have confirmed in my console log that those are coming through just fine.
In my template though, when I use the visible: viewModel[catname] data binding, nothing happens. Not getting any errors though. Any ideas?
—
Note:
Actual template (rails3):
<% @categories.each do |category| %>
<div data-bind="visible: viewModel[<%=category.name%>]">
<%= category.name %>
</div>
<% end %>
Your binding should just be
visible: catname. All bindings are already “scoped” withinviewModel, so you don’t need to reference it in the bindings.See my working example here: http://jsfiddle.net/WpdMZ/. Note that
bananaandpearare set totrue, so their corresponding squares are visible, butappleis set explicitly tofalse, so its square is not visible.In light of your update, you should be able to change this line:
To this: