Skip to main content
Removed tag from the title.
Link
A-Sharabiani
  • 18.9k
  • 20
  • 122
  • 137

knockout.js access Access viewModel in javascript function outside viewModel's scope

removed deprecated tag [context]
Link
Source Link
Adam Levitt
  • 10.5k
  • 27
  • 87
  • 145

knockout.js access viewModel in javascript function outside viewModel's scope

I'm wondering if I can access the knockout.js main viewModel from a method outside the scope of the viewModel itself. Take this example:

function Employee(data) {
  var self = this;
  ko.mapping.fromJS(data, {}, this);
}

function EmployeeViewModel() {
  var self = this;
  this.employees = ko.observableArray([]);

  this.loadEmployees = function() {
    var mappedEmployees= $.map(JSON.parse(data.value), function(item) { return new Employee(item) });
    self.employees (mappedEmployees);
  }
}

// here's the part I'm curious about
$(document).ready(function() {
  ko.applyBindings(new EmployeeViewModel());  

  $("#myLink").click(function() {
     // is there some way to get back into the ko context here?
     // like with ko.dataFor or ko.contextFor?
  });
}