KnockoutJS中嵌套的observable

时间:2015-01-09 20:47:10

标签: javascript knockout.js

我有一个自我描述的定义如下:

var my_data = {
  types: { typeA: {fieldX: { type: "string"}},
           typeB: {fieldY: { type: "string"}} },
  entries: [{ type: "typeA", fieldX: "foo" },
            { type: "typeB", fieldY: "bar" }]
  };

这个想法是'类型'描述了为每个条目索引提供的数据'。此数据用于呈现用于通过RESTful接口编辑JSON数据的表单(每个类型描述字段的输入,其中绑定到条目的字段值)。

我试图在淘汰赛中设置一个表单,允许这些条目进入'要编辑。我首先创建HTML,创建一个用于确定类型的选择框。为此,我将类型字典映射到数组:

function mapDictionaryToArray(dictionary) {
    var result = [];
    for (var key in dictionary) {
        if (dictionary.hasOwnProperty(key)) {
            result.push({ key: key, value: dictionary[key] });
        }
    }

    return result;
}

然后KnockoutJS代码显示条目

<!-- ko foreach: entries -->
            <select data-bind="options: editTestViewModel.types,
                               optionsText: 'key',
                               optionsValue: 'value',
                               value: type,
                               event: { change: editTestViewModel.drawType }"></select>
            <div data-bind="attr: { id: $index() + 'typeFields' }" class="container"></div>
<!-- /ko -->

模型视图:

function EditTestViewModel() {
    var self = this;

    self.entries = ko.observableArray();
    self.types = ko.observable();

    self.setTest = function(test) {
        self.test = test;
        self.types(mapDictionaryToArray(test.types()));
        self.entries(ko.mapping.fromJS(test.entries(), self.stateMapping)());

    };

    self.editTest = function() {
        $('#edit').modal('hide');
        testsViewModel.edit(self.test, {
            entries: self.entries() ,
            types: self.types()
        });
    };

    self.drawType = function(place) {
        home = $('#typeFields');
        home.children().remove();
        for (var field in place.type) {
            tag = $('<div class="input-group">').appendTo(home);
            $('<span class="input-group-addon">' + field + '</span>').appendTo(tag);
            $('<input type="text" class="form-control" data-bind="text: \'test\'">').appendTo(tag);
        }
    };

    self.stateMapping = {
        'type': {
            create: function(options) {
                return options.data
            }
        }
    }
}

var editTestViewModel = new EditTestViewModel();
ko.applyBindings(editTestViewModel, $('#edit')[0]);

我遇到的问题是插入的数据似乎没有被KockoutJS处理。类型选择函数并填充相关字段,但不填充字段值(静态&#34;测试&#34;现在)。 KnockoutJS是否支持动态插入内容,如果是,我是否尝试正确绑定它?

1 个答案:

答案 0 :(得分:1)

感谢大家对OP的评论。

我重写了使用模板。出于某种原因,我认为observable不能用于option.value存储。情况似乎并非如此(https://stackoverflow.com/a/27873057/1440598)。在构造函数中,我现在将类型设置为每个条目的observable。

更改选择会触发模板字段更新: http://fiddle.jshell.net/jhwpn6dy/3/

HTML:

<div data-bind="text: data.test"></div>

<div data-bind="template: { name: 'entry-template', foreach: entries, as: 'entry' }"></div>

<script type="text/html" id="entry-template">
    <h3 data-bind = "text: entry.type">I'm an entry</h3>
    <select data-bind="options: $root.type_keys,
                       optionsText: 'key',
                       optionsValue: 'key',
                       value: entry.type"></select>
    <div data-bind="template: { name: 'field-template', foreach: $root.fieldList(entry), as: 'field' }"></div>
</script>

<script type="text/html" id="field-template">
    <div class="input-group">
      <span class="input-group-addon" data-bind="text: field"></span>
        <input type="text" class="form-control" data-bind="attr: { 'aria-label': field }, value: entry[field]"/>
    </div>
</script>

JS:

var data = {
    types: {
        typeA: {
            fieldX: {
                type: "string"
            }
        },
        typeB: {
            fieldY: {
                type: "string"
            }
        }
    },
    entries: [{
        type: "typeA",
        fieldX: "foo"
    }, {
        type: "typeB",
        fieldY: "bar"
    }],
    test: "Hello"
};

function MainViewModel(data_obj) {
    var self = this;

    self.data = data_obj;
    self.type_keys = mapDictionaryToArray(data_obj.types);    

    for (var entry in data_obj.entries) {
        data_obj.entries[entry].type = ko.observable(data_obj.entries[entry].type);
    }
    self.entries = ko.observableArray(data_obj.entries);
    console.log(self.entries());
}

MainViewModel.prototype.fieldList = function (entry) {
    var self = this;
    var keys = [];

    for (var key in self.data.types[entry.type()]) {
        if (entry.hasOwnProperty(key)) {
            keys.push(key);
        }
    }

    <!-- console.log(entry.type); -->
    return keys;
};

function mapDictionaryToArray(dictionary) {
    var result = [];
    for (var key in dictionary) {
        if (dictionary.hasOwnProperty(key)) {
            result.push({ key: key, value: dictionary[key] });
        }
    }

    return result;
}

var dataViewModel = new MainViewModel(data);

ko.applyBindings(dataViewModel);