我想知道我是否可以从viewModel本身范围之外的方法访问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?
});
}
答案 0 :(得分:52)
您只需将viewmodel存储在可以访问的变量中即可访问它,module and revealing module patterns很好,但您可以将其存储在不会与其他名称冲突的对象中('my'这里):
my = { viewModel: new EmployeeViewModel() };
ko.applyBindings(my.viewModel);
你有正确的想法,你只需要将元素作为你的click函数的参数并将target属性传递给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());
});
});
您可以始终使用the Knockout click binding而不是使用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中($ root是你的基本视图模型,如果clickedOnEmployee函数在你的Employee对象上,你将不需要它):
<ul data-bind="foreach: employees">
<li>
<span data-bind="text: name"></span>
<button data-bind="click: $root.clickedOnEmployee">show</button>
</li>
</ul>