访问视图模型中的javascript函数外视图模型的范围(Access viewModel in j

2019-06-24 13:30发布

我想知道如果我可以访问knockout.js主视图模型从方法视图模型本身的范围之外。 就拿这个例子:

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?
  });
}

Answer 1:

你总是可以仅仅通过存储您的视图模型中的变量,你可以访问,该访问模块,揭示模块的模式很不错,但你可以将其存储在一个对象,不会与其他名称冲突(“我”在这里):

my = { viewModel: new EmployeeViewModel() };
ko.applyBindings(my.viewModel);

你有正确的想法,你只需要采取的元素作为参数传递给你的点击功能,并通过目标属性ko.dataFor或ko.contextFor( 的jsfiddle ):

$(document).ready(function() {
    my.vm = new EmployeeViewModel();
    ko.applyBindings(my.vm);
    $('button').on('click', function(e) {
        alert('you clicked on employee ' + ko.contextFor(e.target).$data.name() +
             ' also known as ' + ko.dataFor(e.target).name());
    });
});​

相反,使用jQuery click事件绑定的,你可以随时使用的淘汰赛点击结合 ,其通过作为第一个参数和事件作为第二个参数(电流模型数据的jsfiddle ):

function EmployeeViewModel() {
  var self = this;

  // skipped some of your code

  this.clickedOnEmployee = function(model, event) {
    // assuming your Employee has a name observable
    alert('You clicked on employee ' + model.name());
  };
}

在HTML($的根是您的基本视图模型,你就不需要它,如果你clickedOnEmployee功能是在你的Employee对象):

<ul data-bind="foreach: employees">
    <li>
        <span data-bind="text: name"></span>
        <button data-bind="click: $root.clickedOnEmployee">show</button>
    </li>
</ul>


文章来源: Access viewModel in javascript function outside viewModel's scope