Tim
Tim

Reputation: 8919

identifying the target of this keyword in knockout subscribe function

I am just now taking my first read of the knockout library website's Getting Started documentation, and have a question about how to specify the target of the this keyword in the callback function sent to the knockout subscribe function, in the context of tracking changes to a set of objects whose properties are being observed.

I need to track 100 objects whose properties are initially null. Every one of those 100 objects can be described by the same view model:

       var myViewModel = {
          personName: ko.observable(null),
          personAge: ko.observable(null)
       };


      var my100 = {
        a1:  myViewModel,
        a2:  myViewModel,
        .
        .
        .
        a100: myViewModel

      }

The second argument of the subscribe() function "defines the value of this in the callback function". http://knockoutjs.com/documentation/observables.html

I am not sure what goes into the second argument when I need to know which one of those 100 objects has changed. When any property in the view model changes from null to a value, or from one value to another value, I want to know which object the change occurred in, e.g. a88.

           myViewModel.personName.subscribe(myCallback, ?, "change");
           myViewModel.personAge.subscribe(myCallback, ?, "change");

Knowing which property was changed would be good too, but it's more important that I know the object whose property has changed.

Upvotes: 2

Views: 1769

Answers (1)

Jeroen
Jeroen

Reputation: 63830

It may be easier to save a reference to the view model itself within the correct scope, so it's available to the callback. This is slightly more readable if you construct your view model with a constructor function:

var Person = function() {
    var self = this;

    self.personName = ko.observable(null);
    self.personAge= ko.observable(null);

    self.personName.subscribe(function(newValue) {
        // "self" is a variable reference to the correct Person here
        // newValue is the new value for the observable
        // calling "myCallback" here allows you to pass those at your leisure
    });
};

See this fiddle for how this would work.

PS. If the callback is short you may not even need a seperate myCallback function, just do the work inside the function inlined in the subscribe call, where you already have a reference to the correct this value (held in the self variable).

Upvotes: 2

Related Questions