I have two text property data Date and City are observables. I need to concatenate two text property data in single div. and apply separate style for both the texts. Current Scenario is used knockoutjs data-bind property :
<div class="date" data-bind="text:Date" />
<div class="city" data-bind="text:City" />
Expected :
<div class="date city" data-bind=" text:Date text:City" />
Output : 2013-05-24 New York
Please guide me how to do this.
Knockout's declarative binding system provides a concise and powerful way to link data to the UI. It's generally easy and obvious to bind to simple data properties or to use a single binding.
Knockout now supports multiple model binding. The ko. applyBindings() method takes an optional parameter - the element and its descendants to which the binding will be activated. This restricts the activation to the element with ID someElementId and its descendants.
KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.
You can't use two of the same binding on an element. Instead, you should create a computed which formats the text using the two values you want to display.
For example (Assuming your Date and City are observables):
viewModel.DateCity = ko.computed(function() {
return viewModel.Date() + " - " + viewModel.City();
});
Then in your data-bind, you just bind to the computed.
<div class="date city" data-bind="text:DateCity" />
Another option is to combine the values in the binding directly.
<div class="date city" data-bind="text: Date() + ' - ' + City()" />
Personally I feel that the computed approach is a cleaner way to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With