Knockout.js Binding to dropdownlist

微笑、不失礼 提交于 2019-12-23 04:35:06

问题


Trying to bind data to a dropdown list,

    function EmailTemplate(data) {
        var self = this;
        self.etId = ko.observable(data.email_template_id);
        self.etTypeId = ko.observable(data.email_template_type_id);
        self.etTitle = ko.observable(data.email_template_title);
        self.etContent = ko.observable(data.email_template_content);
        self.etAppYear = ko.observable(data.app_year);
        self.etSubject = ko.observable(data.subject);
        self.etActive = ko.observable(data.active);
    }

    function EmailTemplateViewModel() {
        var self = this;
        self.ETList = ko.observableArray();

        var uri = '/admin/services/EmailTemplateService.svc/EmailTemplates';
        OData.read(uri, function (data, response) {
            $.each(data.results, function (index, item) {
                self.ETList.push(new EmailTemplate(item));
            });
        });
    }
    $(document).ready(function () {
        ko.applyBindings(new EmailTemplateViewModel());            
    });

HTML markup:

 <select data-bind="options: ETList, value:etId, optionsText: 'etTitle' "class="dropdown"></select>

When I run this I got: Uncaught Error: Unable to parse bindings. Message: ReferenceError: etIdis not defined; Bindings value: options: ETList, value:etId, optionsText: 'etTitle'

When we bind to drop down list, how should we bind the value? and after binding, how should we capture or create dropdown change event in Knockout?


回答1:


When working with <select> options, the value binding will determine which of the options is selected, usually you'll want an observable in your viewmodel (e.g. selectedTemplate) that this is set to. Then this observable will automatically be mapped to the actual object from the observable array. Setting value: etId doesn't make sense since there's no etId in your root viewmodel.

Example: http://jsfiddle.net/antishok/968Gy/

function EmailTemplateViewModel() {
    var self = this;
    self.ETList = ko.observableArray();
    self.selectedTemplate = ko.observable();
    // ...
}

HTML:

<select data-bind="options: ETList, value:selectedTemplate, optionsText: 'etTitle'" class="dropdown"></select>

You might have intended to to optionsValue: 'etId' which would work but is usually a less preferable approach (because the observable's value would now be set to the ID instead of the actual object)



来源:https://stackoverflow.com/questions/15825539/knockout-js-binding-to-dropdownlist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!