简体   繁体   中英

knockout select data bind

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;
    }

It'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 complexity 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM