Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple data-bind in knockout js

Tags:

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.

like image 1000
user2706 Avatar asked Apr 24 '13 11:04

user2706


People also ask

What is data binding in KnockoutJS?

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.

Can we have multiple knockout model?

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.

What is two-way binding in KnockoutJS?

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.


1 Answers

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.

like image 151
Joe Doyle Avatar answered Sep 22 '22 02:09

Joe Doyle