Knockout-Binding only works One-Way

369 views Asked by At

I'm using knockout with typescript for building the UI of my application. I want to use a knockout binding to notify my typescript if something in my UI changes.

My code works, but unfortunately only in one-way. The initial value 5 is shown after page was loaded, but if I change something in the breakTime input, the subscribe-method is never entered.

The selectedDates array contains objects which contain the breakTime properties.

The HTML code:

<!-- ko 'foreach': $root.selectedDates-->
<td>
    <input type="text" name="breakTime" data-bind="value: breakTime()" class="bookingTextBox" />
</td>
<!-- /ko -->

The typescript code:

public breakTime: KnockoutObservable<string>;

constructor(date: Date, viewModel: Booking.BookingViewModel) {    
    this.breakTime = ko.observable("30");
    this.breakTime.subscribe((newValue) => {
        alert(newValue);
    });
}

I never worked with knockout foreach-element before, maybe the error is caused by that. Do I have to do something else ot get this working?

1

There are 1 answers

1
ianaya89 On BEST ANSWER

You need to remove parens from the value binding data-bind="value: breakTime"

The reason is that if you use parens your are binding to the input the result of the observable at the moment that the binding is loaded. Is exactly the same if you do this data-bind="value: 5".

Without parens you are binding to value the whole observable.