问题
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();
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?
Thanks for the help.
回答1:
The fiddle loads a resource that contains all of the choices that live in the sampleProductCategories array: http://knockoutjs.com/examples/resources/sampleProductCategories.js
Each cartLine object has category and product observables to hold the current choice.
For example, here is one of the bindings for the individual cartLine:
<select data-bind='options: sampleProductCategories, optionsText: "name", optionsCaption: "Select...", value: 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.
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' />
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.
来源:https://stackoverflow.com/questions/7881235/knockoutjs-cart-editor-example-questions