Knockoutjs“购物车编辑器"示例问题 [英] knockoutjs 'Cart editor' example questions
问题描述
我试图了解如何观察和映射变量. jsfiddle在此处 http://jsfiddle.net/rniemeyer/adNuR/.以下两行javascript似乎设置了用于观察的变量:
I'm trying to understand how the variables are observed and mapped. The jsfiddle is here http://jsfiddle.net/rniemeyer/adNuR/. The following 2 lines of javascripts seem to set up the variables for observation:
this.category = ko.observable();
this.product = ko.observable();
那么上面两行的技巧如何?它如何知道如何将类别和产品映射到sampleProductCategories []数组中?
So how do the above 2 lines do the tricks? How does it know how to map the category and product into the sampleProductCategories[] array?
感谢您的帮助.
推荐答案
小提琴加载了一个资源,其中包含生活在sampleProductCategories
数组中的所有选择:
The fiddle loads a resource that contains all of the choices that live in the sampleProductCategories
array: http://knockoutjs.com/examples/resources/sampleProductCategories.js
每个cartLine
对象都具有category
和product
观察对象来保存当前选择.
Each cartLine
object has category
and product
observables to hold the current choice.
例如,这是各个cartLine的绑定之一:
For example, here is one of the bindings for the individual cartLine:
<select data-bind='options: sampleProductCategories, optionsText: "name", optionsCaption: "Select...", value: category' />
这表示下拉菜单中的选项应来自sampleProductCategories
.框中的值应为name
属性,并且在进行选择时应将其放入cartLine的category
中.
This says that the options in the dropdown should come from sampleProductCategories
. The value in the box should be the name
property and when a selection is made, it should be put into the category
of the cartLine.
因此,选择后,category
现在等于sampleProductCategories
数组中的相应对象.像这样:
So, when a selection is made, category
now equals the appropriate object from the sampleProductCategories
array. Something like:
{
"products": [{
"name": "1950's Chicago Surface Lines Streetcar",
"price": 26.72
}, {
"name": "1962 City of Detroit Streetcar",
"price": 37.49
}, {
"name": "Collectable Wooden Train",
"price": 67.56
}],
"name": "Trains"
}
现在,第二个下拉绑定看起来像:
Now, the second dropdown binding looks like:
<select data-bind='visible: category, options: category() ? category().products : null, optionsText: "name", optionsCaption: "Select...", value: product' />
如果选择了类别,则会显示此绑定.这些选项来自所选类别的products
数组.选择一个值时,将使用数组中的适当对象填充product
observable.喜欢:
This binding shows up if a category has been selected. The options come from the products
array of the selected category. When a value is selected, then the product
observable will be populated with the appropriate object from the array. Like:
{
"name": "Collectable Wooden Train",
"price": 67.56
}
因此,这些下拉菜单一起提供了嵌套选项.
So, the dropdowns work together to provide nested options.
这篇关于Knockoutjs“购物车编辑器"示例问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!