1

I got ko model:

var Model = function(notes) {
    this.note = ko.observableArray(notes);
}; 

var model = new Model([{"post":"a"},{"post":"b"}]);
ko.applyBindings(model);

And html div:

<div data-bind='foreach: note'>
    <p><span data-bind='text: post'>
    <p><input data-bind='value: post'>
</div>

Here's fiddle: http://jsfiddle.net/DE9bE/

I want to change my span value when new text is typed in input, like in that fiddle: http://jsfiddle.net/paulprogrammer/vwhqU/2/ But it didnt updates. How can i do that in foreach bindings?

Mitra
  • 38
  • 5

3 Answers3

2

The properties of the objects need to be made into observables.

You could do this yourself manually (i've used the plain js array map method here, if you need IE8 support you can use ko.utils.arrayMap for the same purpose):

var Model = function(notes) {
    this.note = ko.observableArray(notes.map(function(note){
        note.post = ko.observable(note.post);
        return note;
    }));
}; 
var model = new Model([{"post":"a"},{"post":"b"}]);
ko.applyBindings(model);

Demo


Or you can use the mapping plugin (seperate js file that you need to include) which does this (recursively) for you.

var Model = function(notes) {
    this.note = ko.mapping.fromJS(notes);
}; 
var model = new Model([{"post":"a"},{"post":"b"}]);
ko.applyBindings(model);

Demo


If you get the whole data object from the server you could also feed it directly:

var model = ko.mapping.fromJS({
    note: [{"post":"a"},{"post":"b"}]
});
ko.applyBindings(model);

Demo

xec
  • 17,349
  • 3
  • 46
  • 54
0

Try this:

HTML

<div data-bind='foreach: note'>
    <p><span data-bind='text: post'></span></p>
    <p><input data-bind='value: post'/></p>
</div>

JavaScript

 var Model = function (notes) {
      this.note = ko.observableArray(notes);
 };
 var Post = function (data) {
     this.post = ko.observable(data);
 };

 var model = new Model([new Post("a"), new Post("a")]);
 ko.applyBindings(model);

Demo

super
  • 2,288
  • 2
  • 21
  • 23
0

What you want is an observable array with observables, or else your span will not be updated since you are changing a non-observable variable, see this post.

KnockoutJS - Observable Array of Observable objects

Community
  • 1
  • 1