Skip to content

Knockout.js Integration

f1v edited this page Jun 11, 2014 · 13 revisions

Example integration with Knockout.js

Mailing list thread: https://groups.google.com/forum/?fromgroups#!topic/select2/L4Alk72y3KQ

JSBin: http://f1v.co/r/e24d52e4

Pasted code for posterity:

Markup

<div data-bind="value: selectedState, select2: { data: states, placeholder: 'Select a State', formatResult: format }" class="select2" style="width: 200px"></div>
<div>
Selected: <span data-bind="text: selectedState"></span>

JavaScript

ko.bindingHandlers.select2 = {
    init: function(el, valueAccessor, allBindingsAccessor, viewModel) {
      ko.utils.domNodeDisposal.addDisposeCallback(el, function() {
        $(el).select2('destroy');
      });
            
      var allBindings = allBindingsAccessor(),
          select2 = ko.utils.unwrapObservable(allBindings.select2);

      $(el).select2(select2);
    }
};

function format(state) {
    var originalOption = state.element;
    return state.text.toUpperCase();
}

function State(id, text, children, disabled) {
  this.id = id;
  this.text = text;
  this.disabled = disabled || false;
  this.children = children;
}
function City(id,text,children,disabled) {
  this.id = id;
  this.text = text;
  this.disabled = disabled || false;
  this.children = children;
}

State.prototype.toString = City.prototype.toString =function() {
  return this.text + "(" + this.id + ")";
};

var ViewModel = function () {
  
    this.states = [
      new State("AL", "Alabama",[],true),
      new State("AK", "Alaska", [ new City("JU", "Juneau")]),
      new State("AZ", "Arizona"),
      /* ... */
      new State("WV", "West Virginia"),
      new State("WI", "Wisconsin"),
      new State("WY", "Wyoming")
    ];
  
     this.selectedState = ko.observable("(none)");

};

ko.applyBindings(new ViewModel());

Clone this wiki locally