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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值