javascript KnockoutJS 绑定到键/值对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11051896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:56:22  来源:igfitidea点击:

KnockoutJS binding to Key/Value pair

javascriptmvvmknockout.js

提问by Loek

I am trying to bind to key/value pair data with KnockoutJS:

我正在尝试使用 KnockoutJS 绑定到键/值对数据:

this.personal = {
  "name" : "Chuck",
  "country" : "USA"
};

In my HTML i use the $data binding:

在我的 HTML 中,我使用 $data 绑定:

<ul data-bind="foreach: personal">

  <li data-bind="text: $data"></li>

</ul>

which results in:

这导致:

[object Object]

[object Object]

Does anybody know how my binding should look like if I want to see this:

如果我想看到这个,有人知道我的绑定应该是什么样子的:

name: Chuck

country: USA

in other words...how I can show the property name and the property value?

换句话说......我如何显示属性名称和属性值?

EDIT: Someone pointed me at: https://github.com/jamesfoster/knockout.observableDictionaryBut I still hope to bind without an extra library

编辑:有人指出我:https: //github.com/jamesfoster/knockout.observableDictionary但我仍然希望在没有额外库的情况下绑定

回答by aholtry

There is an easier way of binding to a key-value pair using Knockout.js. Say you have a key value pair that looks like the following

有一种使用 Knockout.js 绑定键值对的更简单方法。假设您有一个如下所示的键值对

myItems: [
            { Name: 'Item 1', Value: 1},
            { Name: 'Item 3', Value: 3},
            { Name: 'Item 4', Value: 4}
        ],

Just use the following html to bind to the key value pair.

只需使用以下 html 绑定到键值对。

<select data-bind="options: myItems, optionsText: 'Name', optionsValue: 'Value'></select>

References:

参考:

http://knockoutjs.com/documentation/options-binding.html

http://knockoutjs.com/documentation/options-binding.html

回答by Liu Yue

Try something like this:

尝试这样的事情:

<ul data-bind="keyvalue: properties">
    <li>
        <span data-bind="text: key"></span> :
        <span data-bind="text: value"></span>
    </li>
</ul>

For JavaScript:

对于 JavaScript:

function AppViewModel() {
    this.properties = { b: 'c', d: 'e' };
}

ko.bindingHandlers['keyvalue'] = {
    makeTemplateValueAccessor: function(valueAccessor) {
        return function() {
            var values = valueAccessor();
            var array = [];
            for (var key in values)
                array.push({key: key, value: values[key]});
            return array;
        };
    },
    'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        return ko.bindingHandlers['foreach']['init'](element, ko.bindingHandlers['keyvalue'].makeTemplateValueAccessor(valueAccessor));
    },
    'update': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        return ko.bindingHandlers['foreach']['update'](element, ko.bindingHandlers['keyvalue'].makeTemplateValueAccessor(valueAccessor), allBindings, viewModel, bindingContext);
    }
};

ko.applyBindings(new AppViewModel());

回答by Daryl Wright

Create a function in your view model that converts the object property names and values into an array of objects with key and value properties containing the aforementioned name and value.

在您的视图模型中创建一个函数,将对象属性名称和值转换为具有包含上述名称和值的键和值属性的对象数组。

var ExampleViewModel = function () {
    var self = this;

    self.personal = {
        "name": "Loek",
        "country": "Netherlands"
    };

    self.personalList = function () {
        var list = [];

        for (var i in self.personal) if (self.personal.hasOwnProperty(i)) {
            list.push({
                "key": i,
                "value": self.personal[i]
            });
        }

        return list;
    };
};

Your html template should look like the following:

您的 html 模板应如下所示:

<ul data-bind="foreach: personalList()">
    <li data-bind="text: $data.key + ': ' + $data.value"></li>
</ul>

This results in the following output:

这导致以下输出:

  • name: Loek
  • country: Netherlands
  • 姓名:洛克
  • 国家:荷兰

Here's a fiddle with a working example.

这是一个带有工作示例的小提琴。

回答by Nicola Peluchetti

I think you should do

我认为你应该做

<ul data-bind="foreach: personal">
  <li data-bind=" text: country"></li>
  <li data-bind=" text: name"></li>
</ul>?

// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
    // Use an array here
    this.personal = [{
        "name": "Loek",
        "country": "Netherlands"
    }];
}

// Activates knockout.js
ko.applyBindings(new AppViewModel());?

fiddle http://jsfiddle.net/Aw5hx/

小提琴http://jsfiddle.net/Aw5hx/

P.S. i never used knockoutJS before this post so i'm no world expert.

PS我在这篇文章之前从未使用过knockoutJS,所以我不是世界专家。