在Knockoutjs中设置bootstrap selectpicker默认值

时间:2014-08-23 09:38:35

标签: javascript jquery twitter-bootstrap knockout.js

我有以下code,bootstrap-selectpicker包装在自定义绑定中。我正在尝试填充各种邮件提供商的列表。我正确渲染但我无法设置值。请注意我的代码this.selectedEmailProvider = ko.observable('MAILCHIMP');,它应将MAILCHIMP设置为所选项目。

我的自定义绑定可能有问题吗?

/**
* Selectpicker binding
* @type {Object}
*/
ko.bindingHandlers.selectPicker = {
    init: function(element, valueAccessor, allBindingsAccessor) {
        if ($(element).is('select')) {
            if (ko.isObservable(valueAccessor())) {
                ko.bindingHandlers.value.init(element, valueAccessor, allBindingsAccessor);
            }
            $(element).selectpicker().addClass('form-control');
        }
    },
    update: function(element, valueAccessor, allBindingsAccessor) {
        if ($(element).is('select')) {
            var selectPickerOptions = allBindingsAccessor().selectPickerOptions;
            if (typeof selectPickerOptions !== 'undefined' && selectPickerOptions !== null) {
                var options = selectPickerOptions.options,
                    optionsText = selectPickerOptions.optionsText,
                    optionsValue = selectPickerOptions.optionsValue,
                    optionsCaption = selectPickerOptions.optionsCaption;
                if (ko.utils.unwrapObservable(options).length > 0) {
                    ko.bindingHandlers.options.update(element, options, ko.observable({
                        optionsText: optionsText,
                        optionsValue: optionsValue,
                        optionsCaption: optionsCaption
                    }));
                }
            }
            if (ko.isObservable(valueAccessor())) {
                ko.bindingHandlers.value.update(element, valueAccessor);
            }

            $(element).selectpicker('refresh');
        }
    }
};

0 个答案:

没有答案