select2 集成knockoutjs

1. execute scripts when page loading:

ko.bindingHandlers.select2 = {
    init: function(element, valueAccessor, allBindingsAccessor) {
        var options = ko.toJS(valueAccessor()) || {};
        var allBindings = allBindingsAccessor();
        var lookupKey = allBindings.lookupKey;
        setTimeout(function() {
            $(element).select2(options);
        }, 0);

        if (lookupKey) {
            var value = ko.utils.unwrapObservable(allBindings.value);
            $(element).select2('data', ko.utils.arrayFirst(options.data.results, function(item) {
                return item[lookupKey] === value;
            }));
        }

        ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
            $(element).select2('destroy');
        });
    },
    update: function(element) {
        $(element).trigger('change');
    }
};

2. page html tag, Ex:

<select id="form_input1_orientation"></select>

3. data binding :

$("#form_input1_orientation").attr("data-bind",
                "options: orientationCategories, optionsValue: 'Id', optionsText: 'Name',  selectedOptions: install().orientation_1, select2: {}");

4. view modal:

var orientationCategoriesData = [
            {Id: "north", Name: "正北"},
            {Id: "northeast", Name: "东北"},
            {Id: "northwest", Name: "西北"},
            {Id: "east", Name: "正东"},
            {Id: "southeast", Name: "东南"},
            {Id: "south", Name: "正南"},
            {Id: "southwest", Name: "西南"},
            {Id: "west", Name: "正西"}
        ]

self.orientationCategories = ko.observableArray(orientationCategoriesData);

self.orientation_1 = ko.observable(["east"]);

enjoy.

相关推荐