Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

knockout.js - knockoutjs overriding bindinghandlers

Hi I'm trying to set ko up so that on any click handler being called a little bit of custom code is run. Whats the easiest way to add some pre and post code to the 'click' bindings handler?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can either create a custom binding that wraps the click binding or save off references to the original init and update functions of the click binding and replace the real one.

You could either choose to execute some code in the update function which will be triggered when the model value is updated (either by the event handler attached in the init function or programmatically) or execute your code as part of the actual handler. It sounds to me like you want the latter.

Your binding might look like:

(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 out the pre/post code such that at run-time you could override ko.bindingHandlers.click.preOnClick or ko.bindingHandlers.click.postOnClick

Here is a sample: http://jsfiddle.net/rniemeyer/PksAn/

If you need to run custom code in the update function, then you can split it out and run your pre and post code there and execute originalUpdate in between.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...