caloggins
7/18/2016 - 2:07 PM

ko.file.js

(function (factory) {
  // Module systems magic dance.

  if (typeof require === "function" && typeof exports === "object" && typeof module === "object") {
    // CommonJS or Node: hard-coded dependency on "knockout"
    factory(require("knockout"));
  } else if (typeof define === "function" && define["amd"]) {
    // AMD anonymous module with hard-coded dependency on "knockout"
    define(["knockout"], factory);
  } else {
    // <script> tag: use the global `ko` object, attaching a `mapping` property
    factory(ko);
  }
}(function (ko) {

  ko.bindingHandlers.file = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
      $(element).change(function () {
        var file = this.files[0];
        if (ko.isObservable(valueAccessor())) {
          valueAccessor()(file);
        }
      });
    },

    update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
      var file = ko.utils.unwrapObservable(valueAccessor());
      var bindings = allBindingsAccessor();

      if (bindings.fileObjectURL && ko.isObservable(bindings.fileObjectURL)) {
        var oldUrl = bindings.fileObjectURL();
        if (oldUrl) {
          windowURL.revokeObjectURL(oldUrl);
        }
        bindings.fileObjectURL(file && windowURL.createObjectURL(file));
      }

      if (bindings.fileBinaryData && ko.isObservable(bindings.fileBinaryData)) {
        if (!file) {
          bindings.fileBinaryData(null);
        } else {
          var reader = new FileReader();
          reader.onload = function (e) {
            bindings.fileBinaryData(e.target.result);
          };
          reader.readAsText(file);
        }
      }
    }
  
  };

  return {}; // let require js work fine
}));