3
votes

I have a strange problem, where I have an object - lets call it Person - which has the observable properties FirstName and Lastname, and a third computed property called FullName. In my ViewModel I have an observable array of these Person objects. I also have a function to push an empty Person to the array.

Here comes the strange part.

When I add one person, change the FirstName and LastName, the computed FullName becomes the concatenation of the first and last name - this is the expected behaviour. If I then add another person object, change that objects FirstName or LastName property and then return to change the first person FirstName, the computed FullName of both Person objects is now the concatenation of the first and lastname properties of only the last Person.

Here is the code:

function Person(data)
{
    self = this;
    self.FirstName = ko.observable(data !== undefined ? data.FirstName : "");
    self.LastName = ko.observable(data !== undefined ? data.LastName : "");
    self.FullName = ko.computed(function ()
    {
        return self.FirstName() + " " + self.LastName();
    });
};
function ViewModel() {
    var self = this;
    self.People = ko.observableArray([]);

    self.AddPerson = function()
    {
        self.People.push(new Person());        
    }
}

ko.applyBindings(new ViewModel());

...and the problem can be recreated in this Fiddle using following steps:

  1. Press Add
  2. Fill random text in both of the inputs
  3. Observe the concatenated inputs below the button
  4. Press Add again
  5. Fill random text in either of the two new inputs
  6. Change the value of one of the first inputs
  7. Observe that the concatenated inputs are now exactly the same.

How can I get this seemingly simple scenario to work properly?

Any help is appreciated. Thank you in advance.

1

1 Answers

5
votes

Self is being registered as a global variable because of not enclosing it. Change self = this; to var self = this;

http://jsfiddle.net/AkHhJ/2/

this is on my phone so hard to fix code but it works

var self = this;

if you don't state var it is considered to be part of the global scope and shared.