Knockoutjs 覆盖绑定处理程序 [英] knockoutjs overriding bindinghandlers

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

问题描述

我正在尝试设置 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 的引用click 绑定的 > 和 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.

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

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