I'm using KnockoutJS and loading my view model via ajax. Before the load completes, I'd like to show a "Loading..." message, and if no data is loaded, I'd like to show a "No results." message. My initial attempt looks like this:
<ul data-bind="template: { name: 'mentions-template', foreach: mentions.data }">
<li data-bind="visible: mentions.loaded() && mentions.data().length < 1">No mentions</li>
<li data-bind="visible: !mentions.loaded()">Loading...</li>
</ul>
<script type="text/javascript">
var viewModel = {
mentions: {
loaded: ko.observable(false),
data: ko.observableArray()
}
}
function loadData() {
$.post(action, function(result) {
viewModel.mentions.data = ko.mapping.fromJS(result);
viewModel.mentions.loaded(true);
ko.applyBindings(viewModel);
});
}
ko.applyBindings(viewModel);
loadData();
</script>
I expected that the first li element would only show if viewModel.mentions.loaded was false and viewModel.mentions.data contained some items, and that the second li would show up until viewModel.mentions.loaded had been set to false, but both items are displayed at all times. What am I doing wrong?
!in knockout bindings, have you tried== falseinstead? - sellmeadoglielements when it does the binding. - Chrisstatusproperty to my view model and bind it to a<span>in the ui; the actual message is determined in ako.computable. - sellmeadog