Created
September 19, 2013 08:40
-
-
Save fredkingham/6620685 to your computer and use it in GitHub Desktop.
dynamic modal binding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!function(ko){ | |
"use strict"; | |
// var modalElement = "#modal"; | |
var addHiddenDivToBody = function() { | |
var div = document.createElement("div"); | |
div.id = "modal"; | |
document.body.appendChild(div); | |
$(div).text("goodbye"); | |
$(div).addClass("modal hide fade"); | |
return div; | |
}; | |
var createModalElement = function(templateName, viewModel) { | |
// var temporaryDiv = addHiddenDivToBody(); | |
var deferredElement = $.Deferred(); | |
ko.renderTemplate( | |
templateName, | |
viewModel, | |
// We need to know when the template has been rendered, | |
// so we can get the resulting DOM element. | |
// The resolve function receives the element. | |
{}, | |
// The temporary div will get replaced by the rendered template output. | |
document.getElementById("modal") | |
); | |
// Return the deferred DOM element so callers can wait until it's ready for use. | |
return deferredElement; | |
}; | |
ko.bindingHandlers.dynamicModal = { | |
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext){ | |
$("#modal").on("hidden", ko.bindingHandlers.dynamicModal.dismiss); | |
ko.utils.registerEventHandler(element, "click", function(e) { | |
addHiddenDivToBody(); | |
e.preventDefault(); | |
e.stopPropagation(); | |
var templateName = ko.utils.unwrapObservable(valueAccessor()); | |
var viewModel = allBindingsAccessor().getData(); | |
createModalElement(valueAccessor, viewModel); | |
$('#modal').modal('show'); | |
}); | |
}, | |
dismiss: function(){ | |
var $ui = $("#modal"); | |
$ui.each(function (index, element) { ko.cleanNode(element); $(element).remove() }); | |
} | |
}; | |
/* | |
* calls a click handler then dismisses the modal | |
*/ | |
ko.bindingHandlers.proccessModal = { | |
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext){ | |
ko.utils.registerEventHandler(element, "click", function(e) { | |
e.preventDefault(); | |
var response = ko.utils.unwrapObservable(valueAccessor())(); | |
ko.bindingHandlers.proccessModal.loading(true); | |
response.done(function(){ | |
$('#modal').modal('hide'); | |
ko.bindingHandlers.proccessModal.loading(false); | |
}); | |
}); | |
}, | |
loading: ko.observable(false) | |
}; | |
}(ko) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment