2

I am using a foreach template with knock out.

I have a binding in my page

 <div data-bind="template: { name:'myList', foreach: viewModel.myList}</div>

In my template, I have an attr binding on an input:

 data-bind="attr: { value: $data.Desc }"


viewModel.myList.push(listItem);

I then convert my view model to JSON:

 var json = ko.mapping.toJSON(viewModel);

The value in the input is not bound to the observable array. Even if I hard code the value like below it doesn't bind.

data-bind="attr: { value: 1 }"

How do I keep my view model observable array in sync with my input when adding?

More Info - Update

I am populating my initial view model using: viewModel.myList = ko.mapping.fromJS(model);

model is passed to my JavaScript using @Html.Raw(JsonConvert.SerializeObject(Model), which is passed from an MVC controller. It contains a list of objects called 'myList'.

I'm not sure exactly what else to provide (sorry I can't provide a fiddle at the moment due to the dependency on my DB, MVC etc). Does this help answer?

Solution?

It seems I cannot use the attr binding with value - if I move the value binding out side like this:

data-bind="value: $data.Desc, attr: { other attributes here... }

it works. Anyone know why?

2
  • Are you able to provide some more code (html & view model) or a jsfiddle? Commented Jun 4, 2015 at 10:06
  • May be worth to say, that observable array isn't really array of observables, if you want to have observable fields inside an array you have to declare them as well, but anyway: not enough data to answer. Commented Jun 4, 2015 at 10:10

1 Answer 1

2

I think it might be related to how you bind the value on the input as I've seen this a few times, try this:

<input data-bind="value: $data.Desc" />

instead of this:

<input data-bind="attr: { value: $data.Desc }" />

The correct way to bind the value is not through the attribute, I think if it's set as an attribute knockout sets it initially but doesn't care if it changes afterwards.

Sign up to request clarification or add additional context in comments.

2 Comments

haha - thank you - i just posted an edit to that effect. Thanks for the explanation. I will accept this answer asap. PS - thanks for answering despite the hurried (poor quality) question (I'm up against it at work :))
You are welcome, I suspected that was the reason initially as we use knockout and I've seen it a few times, but thought to wait for more info

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.