Knockout kendo dropdown

http://stackoverflow.com/questions/12051943/refresh-kendodropdown-using-knockout-kendo-js-library

by Sergio Sánchez

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.0.0.debug.js"></script>
<link rel="stylesheet" href="http://rniemeyer.github.com/knockout-kendo/css/kendo.common.min.css">
<link rel="stylesheet" href="http://rniemeyer.github.com/knockout-kendo/css/kendo.default.min.css">
<script src="http://cdn.kendostatic.com/2012.1.322/js/kendo.all.min.js"></script>
<script src="http://rniemeyer.github.com/knockout-kendo/js/knockout-kendo.min.js"></script>
<input style='width: 300px' id="availableLanguagesDropdown" data-bind="kendoDropDownList: { dataTextField: 'name', dataValueField: 'id', data: hierarchicalArray, value: selectedChoice }" />
<hr/>

<div data-bind="text: selectedChoice"></div>

<button data-bind="click: removeLanguages">Remove Languages</button>

JavaScript

var arrayofData = [{
  id: 1,
  parentId: null,
  name: 'Parent 1'
}, {
  id: 2,
  parentId: null,
  name: 'Parent 2'
}, {
  id: 3,
  parentId: 1,
  name: 'Son Of Parent 1'
}, {
  id: 4,
  parentId: 2,
  name: 'Son Of Parent 2'
}, {
  id: 5,
  parentId: 3,
  name: 'Grandson of Parent 1'
}, {
  id: 6,
  parentId: null,
  name: 'Parent 3'
}, {
  id: 7,
  parentId: 5,
  name: 'Great-grandson of Parent 1'
}
];

var ViewModel = function() {
  var $scope = this;
  $scope.Languages = ko.observableArray(["one", "two", "three"]);
  $scope.Language = ko.observable("two");

  $scope.dropDown = ko.observable();

  $scope.removeLanguages = function() {
    this.Languages([]);
    this.Language("");
    this.dropDown().text("");
  };
  $scope.hierarchicalArray = ko.observableArray();
	


  var addToHierarchicalArray = function(model) {
    if (model.parentId === null) {
      $scope.hierarchicalArray.push(model);
    } else {
      
      var index = findParentIndex(model.parentId);
      var parent = $scope.hierarchicalArray()[index];
      model.level = parent.level + 1;
      model.name = ' ' + Array(model.level + 1).join("-") + ' '+ model.name;
      $scope.hierarchicalArray.splice(index+1, 0, model);      
    }
  }

  var findParentIndex = function(id) {
  	var indexToReturn = -1;
    $scope.hierarchicalArray().forEach(function(element, index, array) {
      if (element.id === id)
      {
      	indexToReturn = index;
       	return;
      }
      
    });
    return indexToReturn;
  }

  arrayofData.forEach(function(element, index, array) {
    var model = new financialAccountModel(element);
    addToHierarchicalArray(model);
  });
  
  $scope.selectedChoice = ko.observable(2);
  console.log ( ko.toJSON($scope.hierarchicalArray));
};

function financialAccountModel(source) {
  source = source || {};
  var $scope = this;
  $scope.id = source.id;
  $scope.parentId = source.parentId;
  $scope.name = source.name;
  $scope.level = 0;
};


ko.applyBindings(new ViewModel());