Knockoutjs - 加载时触发参数的绑定 [英] knockoutjs - bindings with parameters triggered on load

查看:32
本文介绍了Knockoutjs - 加载时触发参数的绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近做了很多knockoutjs,遇到了一个奇怪的现象.

正如你在这个 fiddle http://jsfiddle.net/hqXjv/ 中看到的,当你为 click: testMethod 然后当点击按钮时触发动作.

正如你在这个 fiddle http://jsfiddle.net/kxTzM/ 中看到的,当你设置绑定到 click: testMethod('hi') 该操作在按钮被点击和页面加载时触发(我猜是 applyBindings)

有参数不是重现问题所必需的,如果您将绑定更改为 click: testMethod() 在第一个小提琴中,您会看到它是在页面加载时触发的.

虽然,是的,我可以向元素添加另一个属性并尝试将其用作参数,但我的问题是,有没有办法将参数传递给knockoutjs 绑定而不触发它们加载.如果这是一个错误,那就这样吧,但我只想知道一种避免它的方法.

解决方案

我认为这个淘汰赛页面上的注释 2"说明了一切:

http://knockoutjs.com/documentation/click-binding.html

您可以使用以下任一方法来避免该问题:

匿名函数:

<button data-bind="click: function(data, event) { myFunction(data, event, 'param1', 'param2') }">点击我</button>

...或...

绑定方法:

<button data-bind="click: myFunction.bind($data, 'param1', 'param2')">点击我</button>

I've been doing a lot of knockoutjs lately, and I came across a strange occurence.

As you can see in this fiddle http://jsfiddle.net/hqXjv/ when you set up a binding to click: testMethod then the action fires when the button is clicked.

As you can see in this fiddle http://jsfiddle.net/kxTzM/ when you setup the binding to click: testMethod('hi') the action fires both when the button is clicked and on page load (I'm guessing on applyBindings)

Having a parameter isn't necessary to reproduce the problem, if you change the binding to click: testMethod() in the first fiddle, you see that it is triggered on page load.

While, yes, I could add another attribute to the element and attempt to use that as a parameter, my question is, is there a way to pass parameters to knockoutjs bindings without triggering them onload. If this is a bug, so be it, however I just want to know a way to avoid it.

解决方案

I think "Note 2" on this knockout page explains it all:

http://knockoutjs.com/documentation/click-binding.html

You can avoid the problem by either using:

Anonymous functions:

<button data-bind="click: function(data, event) { myFunction(data, event, 'param1', 'param2') }">Click me</button>

... or ...

The bind method:

<button data-bind="click: myFunction.bind($data, 'param1', 'param2')">Click me</button>

这篇关于Knockoutjs - 加载时触发参数的绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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