select2 통합 knockoutjs

2264 단어 knockout
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.

좋은 웹페이지 즐겨찾기