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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以创建一个包装
click
绑定的自定义绑定,也可以保存对click 的原始
绑定并替换真实的。init
和update
函数的引用您可以选择在
update
函数中执行一些代码,这些代码将在模型值更新时触发(通过 init 函数中附加的事件处理程序或以编程方式),或者将您的代码作为实际的处理程序。在我看来你想要后者。您的绑定可能如下所示:
我拆分了前/后代码,以便在运行时您可以覆盖
ko.bindingHandlers.click.preOnClick
或ko.bindingHandlers.click.postOnClick
代码>这是一个示例: http://jsfiddle.net/rniemeyer/PksAn/
如果您需要在更新函数中运行自定义代码,那么您可以将其拆分出来并在那里运行您的前后代码并执行
之间的originalUpdate
。You can either create a custom binding that wraps the
click
binding or save off references to the originalinit
andupdate
functions of theclick
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:
I split out the pre/post code such that at run-time you could override
ko.bindingHandlers.click.preOnClick
orko.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.