Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A first attempt at a knockout custom binding. This one will display an array of messages in a twitter bootstrap alert box. The priority option allows you to choose the type of alert that is displayed. jQuery animations are used to make the alert slide in and fade out. http://bthurley.wordpress.com/2013/10/08/a-first-knockout-custom-binding-to-di…
define(["jquery", "knockout"], function($, ko)
{
"use strict";
/**
* Binds an observable array to a dismissable alert box
*/
ko.bindingHandlers.alertList =
{
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext)
{
var data = valueAccessor();
var priority = allBindingsAccessor().priority;
var alertClass = "alert-danger";
if(priority === "info")
{
alertClass = "alert-info";
}else if(priority === "warning")
{
alertClass = "alert-warning";
}else if(priority === "success")
{
alertClass = "alert-success";
}
element.style.display = "none";
element.innerHTML = "<button type=\"button\" data-hide=\"alert\" class=\"close\">x</button>" +
"<h4 class=\"alert-heading\">Error</h4>";
element.className = "alert " + alertClass + " alert-dismissable";
var ul = document.createElement("ul");
ul.className = "list-unstyled";
ul.innerHTML = "<li><span data-bind='text: message'></span></li>";
element.appendChild(ul);
ko.applyBindingsToNode(ul, { foreach: data });
return { controlsDescendantBindings: true };
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext)
{
var value = ko.utils.unwrapObservable(valueAccessor());
if(value.length>0)
{
$(element).slideDown();
} else {
$(element).fadeOut("fast");
}
}
};
});
$(document).on("click", "[data-hide]", function()
{
$(this).closest("." + $(this).attr("data-hide")).fadeOut("fast");
});
<div data-bind="alertList: errors, priority: 'error'"></div>
define(["jquery", "knockout", "mapping"], function($, ko, mapping)
{
"use strict";
var FormVM = function FormVM()
{
var self = this;
self.errors = ko.observableArray();
self.submit = function()
{
$.ajax( {
url: "test",
type: "post",
error: function(data)
{
self.errors(data.responseJSON);
}
} );
};
};
return FormVM;
});
[{"message":"may not be null","messageTemplate":"{javax.validation.constraints.NotNull.message}","path":"User.createUser.arg0.password","invalidValue":null},{"message":"may not be null","messageTemplate":"{javax.validation.constraints.NotNull.message}","path":"User.createUser.arg0.supportedLanguage","invalidValue":null},{"message":"may not be null","messageTemplate":"{javax.validation.constraints.NotNull.message}","path":"User.createUser.arg0.username","invalidValue":null}]

What if we want to pass-in the priority as an option from the ViewModel? Can you suggest a way to achieve this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment