1 // For certain common events (currently just 'click'), allow a simplified data-binding syntax
2 // e.g. click:handler instead of the usual full-length event:{click:handler}
3 function makeEventHandlerShortcut(eventName) {
4 ko.bindingHandlers[eventName] = {
5 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
6 var newValueAccessor = function () {
8 result[eventName] = valueAccessor();
11 return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindings, viewModel, bindingContext);
16 ko.bindingHandlers['event'] = {
17 'init' : function (element, valueAccessor, allBindings, viewModel, bindingContext) {
18 var eventsToHandle = valueAccessor() || {};
19 ko.utils.objectForEach(eventsToHandle, function(eventName) {
20 if (typeof eventName == "string") {
21 ko.utils.registerEventHandler(element, eventName, function (event) {
22 var handlerReturnValue;
23 var handlerFunction = valueAccessor()[eventName];
28 // Take all the event args, and prefix with the viewmodel
29 var argsForHandler = ko.utils.makeArray(arguments);
30 viewModel = bindingContext['$data'];
31 argsForHandler.unshift(viewModel);
32 handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
34 if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
35 if (event.preventDefault)
36 event.preventDefault();
38 event.returnValue = false;
42 var bubble = allBindings.get(eventName + 'Bubble') !== false;
44 event.cancelBubble = true;
45 if (event.stopPropagation)
46 event.stopPropagation();