Perf Tip #3 - All bindings fire together

http://www.knockmeout.net/2012/06/knockoutjs-performance-gotcha-3-all-bindings.html

by Doug Hill

HTML

<script src="https://github.com/downloads/knockout/knockout/knockout-2.1.0.js"></script>
<script src="http://bestware.us/knockout/knockout-repeat.js"></script>
<input data-bind="value: numberOfOptions" /> # of options

<hr/>

<select data-bind="options: options, value: selected"></select> Options rebuilt on each change

<hr/>

<select data-bind="isolatedOptions: options, value: selected2"></select> Options tracked independently

<hr/>

<select data-bind="value: selected3">
    <option data-bind="repeat: options" data-repeat-bind="attr: { value: $item }, text: $item"></option>
</select> Options built separately

JavaScript

ko.bindingHandlers.isolatedOptions = {
    init: function(element, valueAccessor) {
        var args = arguments;
        ko.computed({
            read:  function() {
               ko.utils.unwrapObservable(valueAccessor());
               ko.bindingHandlers.options.update.apply(this, args);
            },
            owner: this,
            disposeWhenNodeIsRemoved: element
        });
    }        
};


var ViewModel = function() {
   this.numberOfOptions = ko.observable(5000);
   this.options = ko.computed(function() {
       var i, 
           result = [],
           count = +this.numberOfOptions();

       for (i = 0; i < count; i++) {
           result.push("option " + i);   
       }
        
        return result;
   }, this);
    
   this.selected = ko.observable();
   this.selected2 = ko.observable();
   this.selected3 = ko.observable();
};


ko.applyBindings(new ViewModel());