[英]Knockout Mapping - fromJS - failing on a simple example
I'm trying to figure out what I'm misunderstanding with Knockout's mapping library. 我试图弄清楚我对Knockout的映射库有什么误解。 I've stripped it down to a simple example, and still can get it to fail (rather, not update with the mapped variables) with the
fromJS
call. 我已经将它简化为一个简单的例子,并且仍然可以通过
fromJS
调用使其失败(而不是使用映射的变量进行更新)。
What am I getting fundamentally wrong in this example? 在这个例子中,我从根本上犯了什么错误?
// Here's my view model
var ViewModel = function() {
this.firstName = ko.observable('first');
this.lastName = ko.observable('last');
};
var myVM = new ViewModel();
ko.applyBindings(myVM); // Apply to Knockout (works)
myVM.lastName('maiden name'); // Test an update (works)
var newData = {firstName: 'new', lastName: 'person'};
// Try update the ViewModel
ko.mapping.fromJS(newData, myVM); //(No update, or error)
// Intended result - UI updates to 'new person'
And the corresponding view: 和相应的观点:
<div class='liveExample' >
<p>First name: <input data-bind='value: firstName' /></p>
<p>Last name: <input data-bind='value: lastName' /></p>
</div>
My JS Fiddle example . 我的JS小提琴例子 。
The ko.mapping.fromJS
handles the parameters a little bit tricky (see my answer here ), so the second parameter is normally the mapping options: ko.mapping.fromJS
处理参数有点棘手(请参阅我的答案 ),所以第二个参数通常是映射选项:
ko.mapping.fromJS(newData, {} /* mapping options */, myVM);
I found how to use only 2 data parameters. 我发现如何只使用2个数据参数。
Create your ViewModel as a mapping of your original data, then use ko.mapping.fromJS(data, ViewModel)
. 创建ViewModel作为原始数据的映射 ,然后使用
ko.mapping.fromJS(data, ViewModel)
。
Explanation 说明
Knockout uses a property called mappingProperty = "__ko_mapping__"
to identify when data has been previously mapped. Knockout使用名为
mappingProperty = "__ko_mapping__"
的属性来识别先前已映射数据的时间。 If found, it will set the second parameter as the target (ViewModel in this case). 如果找到,它将第二个参数设置为目标(在本例中为ViewModel)。
Excerpt from the debug version of ko.mapping.js : 摘自ko.mapping.js的调试版本:
var mappingProperty = "__ko_mapping__";
[...]
if (arguments.length == 2) {
if (arguments[1][mappingProperty]) {
target = arguments[1];
} else {
options = arguments[1];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.