Pregunta

I have a very simple model set up where I have a list of email addresses stored in an observableArray. These are editable via a foreach data binding, but the binding only seems to be one way. When I change the value in the text box, the change is not reflected in the model. However, if I update another field outside of the array, that update is triggering foreach binding update.

I have a fiddle demonstrating this here:

http://jsfiddle.net/xeLcy/1/

And the relevant html is here

<div data-bind="foreach: addresses">
  <input type="text" data-bind="value: $rawData.address, valueUpdate: 'input'" />
  <button data-bind="click: $parent.removeAddress">Remove</button>
  <br/>
</div>

Where the model is

var Model = function() {
  var self = this;
  self.modelName = ko.observable("modelName");
  self.maxCount = 4;
  self.addresses = ko.observableArray();

  self.addUser = function(email) {
    self.addresses.push({address: email});
  };

  self.removeAddress = function(email) {
     self.addresses.remove(email);
  };

  self.hasEmpty = ko.computed(function() {
      var hasBlank = false;
      ko.utils.arrayForEach(self.addresses(), function(item){     
         if (item.address === ""){
           hasBlank = true;
           return;
         }
      });
      return hasBlank;
  });

  self.allowAddMore = ko.computed(function() {
    return self.hasEmpty() === false && self.addresses.length <= self.maxCount;
  });

  self.addNew = function() {
    if (!self.hasEmpty()){
      self.addresses.push({address: ''});
    }
  };
};
¿Fue útil?

Solución

Your address is not an observable. Change your addUser to :

self.addUser = function(email) {
    self.addresses.push({address: ko.observable(email)});
};

See updated fiddle: http://jsfiddle.net/nyothecat/xeLcy/2/

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top