3

当为视图模型使用 KO 映射插件,然后绑定到选择时,未设置该值。

jsFiddle:

http://jsfiddle.net/JerryClinesmith/pCn9E/

HTML:

<h1>With ko.mapping (manager not set)</h1>
<div id="option-mapping">
    <select data-bind="options: availManagers, value: manager, optionsText: 'name', optionsCaption: 'Pick one'"></select>
    <div data-bind="text: json"></div>
</div>

<h1>Without ko.mapping (manager is set)</h1>
<div id="option-no-mapping">
    <select data-bind="options: availManagers, value: manager, optionsText: 'name', optionsCaption: 'Pick one'"></select>
    <div data-bind="text: json"></div>
</div>​

JavaScript:

var origData = {
manager: {},
availManagers: [
    {id: 1, name: 'Tom'},
    {id: 2, name: 'Joe'},
    {id: 3, name: 'James'}]
};

var ViewModel = function(data) {
    var self = this;

    ko.mapping.fromJS(data, {}, self);

    self.json = ko.computed(function() {
        return ko.toJSON(ko.mapping.toJS(self));
    });
};

var ViewModelNoMapping = function(data) {
    var self = this;

    self.manager = ko.observable(data.manager);
    self.availManagers = ko.observableArray(data.availManagers);

    self.json = ko.computed(function() {
        var obj = ko.toJS(self);
        delete obj.json;
        return ko.toJSON(obj);
    });
};

var vm = new ViewModel(origData);
var vm2 = new ViewModelNoMapping(origData);
ko.applyBindings(vm, document.getElementById('option-mapping'));
ko.applyBindings(vm2, document.getElementById('option-no-mapping'));​

没有映射插件的视图模型似乎可以按预期工作。

4

1 回答 1

0

我之前用空白对象遇到过同样的问题,它似乎没有创建一个可观察的......这意味着 manager 是一个普通对象,这意味着计算永远不会触发。

例如,将其更改为...(注意:我将 manager: {} 更改为 manager: '' 然后给它一些转换为可观察的东西。然后使事情顺利进行...也将转换为 json 函数,因为另一个似乎没有显示经理的价值观。

 manager: '',
    availManagers: [
        {
        id: 1,
        name: 'Tom'},
    {
        id: 2,
        name: 'Joe'},
    {
        id: 3,
        name: 'James'}]
};

var ViewModel = function(data) {
    var self = this;
    //self.manager = ko.observable();
    ko.mapping.fromJS(data, {}, self);
    self.json = ko.computed(function() {
         var obj = ko.toJS(self);
        delete obj.json;
        return ko.toJSON(obj);
    });
};

我不确定这是否是映射插件中的错误,既没有转换为可观察对象,也没有转换为正确的 json 进行显示。

为了确认,我下载了映射插件并编写了测试:-

test('mapping an object creates a observable', function () {
    var data = {
        a : {}      
    };

    var mapped = ko.mapping.fromJS(data);  
  equal(ko.isObservable(mapped.a), true);
});

结果

failed
Expected:   true
Result:     false
Diff:   true false 
Source:     at Object.<anonymous> (file:///C:/OpenSourceReps/Knockout/mapping/spec/mappingBehaviors.js:1635:3)
于 2012-06-05T04:25:21.670 回答