Knockoutjs overriding bindings

Hey. I am trying to set ko so that some user code is executed on any click handler. The easiest way to add some preliminary and postal code to the 'click' binding handler?

+6
source share
1 answer

You can create a custom binding that wraps the click binding or stores links to the original init and update functions of the click binding and replaces the real one.

You can either select some code in the update function that will fire when the model value is updated (either by an event handler connected to the init function, or programmatically), or execute your code as part of the actual handler. It sounds like you want the latter.

Your binding might look like this:

 (function() { var originalInit = ko.bindingHandlers.click.init, originalUpdate = ko.bindingHandlers.click.update; ko.bindingHandlers.click = { init: function(element, valueAccessor, allBindingsAccessor, viewModel, context) { var wrappedValueAccessor = function() { return function(data, event) { //run some pre code ko.bindingHandlers.click.preOnClick.call(viewModel, data, event); valueAccessor().call(viewModel, data, event); //run some post code ko.bindingHandlers.click.postOnClick.call(viewModel, data, event); }; }; originalInit(element, wrappedValueAccessor, allBindingsAccessor, viewModel, context); }, update: originalUpdate, preOnClick: function(data, event) { alert("pre code for " + data.id); }, postOnClick: function(data, event) { alert("post code for " + data.id); } }; })(); 

I split the pre / post code so that at runtime you could override ko.bindingHandlers.click.preOnClick or ko.bindingHandlers.click.postOnClick

Here is an example: http://jsfiddle.net/rniemeyer/PksAn/

If you need to run your own code in the update function, you can split it and run your pre-mail and postal code there and execute originalUpdate between them.

+16
source

Source: https://habr.com/ru/post/906847/


All Articles