KNOCKOUT.JS - preventBubblePropagation
by Abra Cadabra
HTML
<div class="outer" data-bind="click: toggleColor, css: bgColor">
<p class="center">
<input type="text" data-bind="preventBubble: 'click'">
</p>
</div>
CSS
.outer {
cursor: pointer;
padding-bottom: 5px;
padding-top: 5px;
width: 250px;
}
.center {
text-align: center;
}
.green {
background-color: green;
}
.yellow {
background-color: yellow;
}
JavaScript
ko.bindingHandlers.preventBubble = {
init: function(element, valueAccessor) {
var eventName = ko.utils.unwrapObservable(valueAccessor());
ko.utils.registerEventHandler(element, eventName, function(event) {
event.cancelBubble = true;
if (event.stopPropagation) {
event.stopPropagation();
}
});
}
};
var ViewModel = function () {
_this = this;
_this.bgColor = ko.observable("green");
_this.toggleColor = function () {
oldColor = _this.bgColor();
if (oldColor === "green") {
_this.bgColor("yellow");
} else {
_this.bgColor("green");
}
};
};
ko.applyBindings(new ViewModel());