我的viewmodel是这样的:
var viewModel = function(){
var self = this;
self.title = ko.observable('Hello World');
self.rows = ko.observableArray();
self.on_click = function(){
alert('Hello World');
var data = [
{
id : 1,
x : 1,
y : 2,
z : 3,
},
{
id : 2,
x : 4,
y : 5,
z : 6,
},
{
id : 3,
x : 7,
y : 8,
z : 9,
}
];
self.rows(ko.unwrap(ko.mapping.fromJS(data, viewModelRow)));
alert(self.rows());
};
};
var viewModelRow = function(){
var self = this;
self.id = ko.observable();
self.x = ko.observable();
self.y = ko.observable();
self.z = ko.observable();
self.mthd = function(){
alert('Just Clicked');
};
};
vm = new viewModel();
ko.applyBindings(vm);
我的HTML是这样的:
<body>
<h1 data-bind="text:title"></h1>
<div data-bind="foreach: rows">
<table>
<tr>
<td data-bind="text : id"></td>
<td data-bind="text: x"></td>
<td data-bind="text: y"></td>
<td data-bind="text: z"></td>
<td><button type="button" data-bind="click: mthd">btn</button></td>
</tr>
</table>
</div>
<button type="button" data-bind="click: on_click">button</button>
</body>
使用 viewModelRow 视图模型上的数据执行映射时,会抛出错误
ReferenceError: mthd is not defined
我希望所有json数据映射与 viewModelRow 以及名为 mthd 的方法在 viewModelRow 中定义。 请帮忙。 JSFIDDLE LINK :http://jsfiddle.net/enabqm3d/5/
答案 0 :(得分:1)
答案 1 :(得分:0)
您正在以错误的方式使用映射插件。 fromJS
函数有三个参数:
fromJS(data, mappingDefinition, mappingTarget);
mappingDefinition
定义了在映射期间应该执行的规则,例如,从数据创建某些对象,如下所示:
var ViewModel = function(){
var self = this;
self.title = ko.observable('Hello World');
self.rows = ko.observableArray();
self.init = function(){
var data = {
rows: [
{id : 1, x : 1, y : 2, z : 3,},
{id : 2, x : 4, y : 5, z : 6,},
{id : 3, x : 7, y : 8, z : 9,}
]
};
ko.mapping.fromJS(data, {
rows: {
create: function (options) {
return new ViewModelRow(options.data);
}
}
}, self);
};
};
var ViewModelRow = function(data){
var self = this;
// think whether these properties really need to be observable
self.id = ko.observable(data.id);
self.x = ko.observable(data.x);
self.y = ko.observable(data.y);
self.z = ko.observable(data.z);
self.mthd = function(){
alert('Just clicked ' + self.id() );
};
};
var vm = new ViewModel();
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<h1 data-bind="text:title"></h1>
<div data-bind="foreach: rows">
<table>
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: x"></td>
<td data-bind="text: y"></td>
<td data-bind="text: z"></td>
<td><button type="button" data-bind="click: mthd">btn</button></td>
</tr>
</table>
</div>
<button type="button" data-bind="click: init">init viewmodel</button>
通读the documentation,读起来甚至不是很多。