0

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: ''});
    }
  };
};

1 Answer 1

3

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/

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

1 Comment

Thanks! Knew I had to be missing something simple.

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.