Knockout.js重写绑定处理程序 [英] knockoutjs overriding bindinghandlers

查看:153
本文介绍了Knockout.js重写绑定处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试设置ko,以便在所有被单击的单击处理程序上运行一些自定义代码. 将最简单的代码添加到单击"绑定处理程序中的最简单方法是什么?

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?

推荐答案

您可以创建用于包装click绑定的自定义绑定,也可以保存对init和update函数的引用>绑定并替换真实的.

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.

您可以选择在update函数中执行一些代码,这些代码将在更新模型值时触发(通过init函数中附加的事件处理程序或以编程方式),或者将代码作为实际代码的一部分执行处理程序.在我看来,您想要后者.

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);
        }
    };
})();

我拆分了前/后代码,以便在运行时可以覆盖ko.bindingHandlers.click.preOnClickko.bindingHandlers.click.postOnClick

I split out the pre/post code such that at run-time you could override ko.bindingHandlers.click.preOnClick or ko.bindingHandlers.click.postOnClick

以下是示例: http://jsfiddle.net/rniemeyer/PksAn/

如果需要在更新功能中运行自定义代码,则可以将其拆分并在其中运行前后代码,然后在两者之间执行originalUpdate.

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.

这篇关于Knockout.js重写绑定处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆