Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

knockout.js - Binding select2 with knockout

I'm new to knockout and trying to get my select2 to play nicely with my knockout bindings.

All I want to do is bind accounts array to my select2 (this works) and then have the initial value set when the binding occurs. I for some reason can not get this to work. Also noticed that the init and update function get called initially, but anytime I change the value of the select2 dropdown, the update function is not being triggered.

Any help would be appreciated.

HTML

 <div class="col-sm-12 col-md-3">
   <fieldset class="form-group">
     <label data-bind="attr:{for:'job'+laborDetailId()}">Job</label>
     <select class="select2" data-bind="attr:{id:'job'+laborDetailId()},updateaccountdropdown: {value:account(),data:accounts,width:'100%'}">
     </select>
   </fieldset>
 </div>

JS

var accounts = [{"id":-1,"text":"","description":null}, {"id":25,"text":"J13002","description":null}, {"id":28,"text":"J13053","description":null}];

var LaborListModel = function(laborModels) {
  var self = this;

  //contains all labor models
  self.labordetails = ko.observableArray(laborModels);
  self.selectedAccount = ko.observable();

  //bindings
  ko.bindingHandlers.updateaccountdropdown = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
            $(element).select2('destroy');
        });

        var allBindings = allBindingsAccessor(),
            select2 = ko.utils.unwrapObservable(allBindings.updateaccountdropdown);
        $(element).select2(select2);
    },
    update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var allBindings = allBindingsAccessor();
        if ("value" in allBindings) {
            var val = ko.utils.unwrapObservable(valueAccessor());
            $(element).val(val.id).trigger('change');
        }
    }
  };
}

getAllLaborDetails().done(function(result) {
   loadAccounts().done(function(_accounts) {
     accounts = _accounts;
     for (var i = 0; i < result.length; i++) {
       //LaborModel
       var laborDetails = [];
       laborDetails.push(new LaborModel(
         result[i].labourDetailId,
         result[i].account,
         result[i].categoryModel,
         result[i].description,
         result[i].timeStamp,
         result[i].hour
       ));
     }
     var vm = new LaborListModel(laborDetails);
     ko.applyBindings(vm);
   });
})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Hope this "select2" custom binding helps you:

ko.bindingHandlers.select2 = {
    after: ["options", "value"],
    init: function (el, valueAccessor, allBindingsAccessor, viewModel) {
        $(el).select2(ko.unwrap(valueAccessor()));
        ko.utils.domNodeDisposal.addDisposeCallback(el, function () {
            $(el).select2('destroy');
        });
    },
    update: function (el, valueAccessor, allBindingsAccessor, viewModel) {
        var allBindings = allBindingsAccessor();
        var select2 = $(el).data("select2");
        if ("value" in allBindings) {
            var newValue = "" + ko.unwrap(allBindings.value);
            if ((allBindings.select2.multiple || el.multiple) && newValue.constructor !== Array) {
                select2.val([newValue.split(",")]);
            }
            else {
                select2.val([newValue]);
            }
        }
    }
};

$(document).ready(function(){
    var data = ko.observableArray([{id: 1, text: "A"}, {id: 2, text: "B"}]);
    var value = ko.observable();
    ko.applyBindings({data: data, value: value});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.full.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.css" />

<span>Selected value: </span>
<span data-bind="text: value"></span>

<div style="width: 350px; margin-top: 20px;">
   <select style="width: 100%;" data-bind="value: value, valueAllowUnset: true, options: data, optionsText: 'text', optionsValue: 'id', select2: { placeholder: 'Select an option...', allowClear: true }"></select>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...