Hi i have a object array which holds some values and i want to put it in a data bind but then on a event change pass in the id of the chosen selected option.
i have so far:
knockout:
<select data-bind="options: Model.Products,
optionsText: 'Name',
event: { change: function(){Model.TestFunction(Model.Products.Id);} }"
></select>
how my object is structured example:
Model.Products():
0: Object
Cost: 0
Id: "2e481911-cff3-e411-80cf-000d3ab07471"
Name: "Product 1"
__proto__: Object
javascript
TestFunction: function (o){
var test = o;
}
Hi i have a object array which holds some values and i want to put it in a data bind but then on a event change pass in the id of the chosen selected option.
i have so far:
knockout:
<select data-bind="options: Model.Products,
optionsText: 'Name',
event: { change: function(){Model.TestFunction(Model.Products.Id);} }"
></select>
how my object is structured example:
Model.Products():
0: Object
Cost: 0
Id: "2e481911-cff3-e411-80cf-000d3ab07471"
Name: "Product 1"
__proto__: Object
javascript
TestFunction: function (o){
var test = o;
}
Share
Improve this question
asked May 6, 2015 at 14:29
user4058171user4058171
2631 gold badge4 silver badges10 bronze badges
2
- Subscribe to the selected product's observable. You could call your function in there. – CrimsonChris Commented May 6, 2015 at 14:32
- can you give me a example with my code? – user4058171 Commented May 6, 2015 at 14:32
1 Answer
Reset to default 5It's better to bind an observable to the select element's value.
First add an observable to your view model (I'm assuming Model
is your view model and I'll follow your pascal case):
Model.SelectedProduct = ko.observable();
Then bind the observable to the select element:
<select data-bind="options: Model.Products, optionsText: 'Name', value: Model.SelectedProduct"></select>
And you can subscribe to the observable which will execute your function when the observable changes value:
Model.SelectedProduct.subscribe(function(product) {
Model.TestFunction(product.Id);
});
The reason why it's better to do this is because in MVVM you want to keep as much logic as possible in the view model so that the view focuses exclusively on presentation. It's a separation of concerns.
For example, when changing the selected product, if you want to ensure that Model.TestFunction
will be executed then doing it this way ensures this regardless of what's going on in the view. If you move this logic to the view, you are opening yourself up to potential errors and increasing the plexity and amount of work required to support all circumstances when the selected product changes. Additionally, you will need to remember to add this additional logic which will create bugs when you forget to do so.