0

LIVE DEMO

Consider the following example:

HTML:

<div data-bind="with: job">
  <div data-bind="foreach: tasks">
    <div>
      <span data-bind="text: $data"></span>
      <span data-bind="click: $parent.allDone">(Done)</span>
    </div>
  </div>
</div>

JS:

ko.applyBindings(function() {
  this.job = {
    tasks: ['Buy milk', 'Sleep', 'Work', 'Praise'],
    allDone: function(data) {
      console.log(this);
      console.log(data);
    }
  };
});

Could you clarify the following points:

  1. Why the value of this in allDone is not job? Isn't allDone called via $parent who is the job?
  2. Is there a way to call allDone on click such that the value of this would be job?
  3. The value of this and data seems similar, but not quite the same:

    this -> String {0: "S", 1: "l", 2: "e", 3: "e", 4: "p", length: 5}

    data -> Sleep

    What is the difference?

Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746

1 Answers1

2
  1. this is operating under the scope of the allDone function, so it will not refer to job. allDone is being called via $parent, in this case the job, but that is in the data-binding syntax - that won't mean that your this in the Javascript will refer to job.

  2. Yes, you can use set the value of this for the job to another variable. The common way to do it is to use var self = this. You can then refer to the parent object (job) via self within the scope of child functions. See fiddle

    var job = function () {
        var self = this;
    
        this.tasks = ['Buy milk', 'Sleep', 'Work', 'Praise'];
        this.allDone = function (data) {
            console.log(self); // refers to the parent job now
            console.log(data); // refers to the current item in the data-bound array
        };
    };
    
    ko.applyBindings(new job());
    
  3. Your original this was treating the simple string as a new Object(data). Using your original code, new Object(data) --> String {0: "S", 1: "l", 2: "e", 3: "e", 4: "p", length: 5}

    Refer to this SO post for more details. Another post to reference is this SO post on Property value of a String object in JavaScript

Community
  • 1
  • 1
rwisch45
  • 3,692
  • 2
  • 25
  • 36