将参数传递给knockoutjs viewmodel中的函数 [英] Passing parameters to a function in knockoutjs viewmodel
问题描述
我有这样的锚标签
<a href="#" class="btn btn-success order-btn" data-bind="attr:{'data-tiername':$data.tierName, 'data-identifier' : $parent.identifier}, click: $root.setPath.bind($data,$data.tierName, $parent.identifier)">Send values</a>
在视图模型中
var appViewModel = {
setPath: function (data, tier, identifier) {
alert(data);
alert(tier);
alert(identifier);
},
...........
...........
}
结果是一些knockoutjs核心代码显示在警报消息中(可能是observable()、dependentObservable()函数和[Object object]的定义,当用JSON.stringify警报时为空)
The result is some knockoutjs core code being displayed in alert message (possibly definitions of observable(),dependentObservable() functions and [Object object] which is empty when alerted with JSON.stringify)
为什么会这样?
data-bind="attr:{'data-tiername':$data.tierName, 'data-identifier' : $parent.identifier}
但不是这个:
click: $root.setPath.bind($data,$data.tierName, $parent.identifier)
注意 tierName 是一个 observable(), identifier 是 calculate()
note that tierName is an observable(), identifier is computed()
在哪里可以找到有关 bind() 的更多信息??
Where can I find more about bind() ??
推荐答案
由于 tierName
和 identifier
是可观察对象,您需要调用它们来访问它们的值:
Since tierName
and identifier
are observables, you need to call them to access to their values:
click: $root.setPath.bind($data, $data.tierName(), $parent.identifier())
此外,bind()
中的第一个参数将绑定到 setPath
中的 this
,所以我猜你需要这样的东西:
Also, first argument in bind()
will be bound to this
in setPath
, so I guess you need something like this:
click: $root.setPath.bind(/*will be bound to this*/ $root, $data,
$data.tierName(), $parent.identifier())
最后,如果 $data
本身是一个 observable(不清楚它是否来自你的代码),那么你也需要调用它:
Finally, if $data
itself is an observable (which is not clear if it is from you code), then you need to call it as well:
click: $root.setPath.bind($root, $data(), $data().tierName(), $parent.identifier())
另请记住 bind 已在 ECMAScript 5 中引入,因此它可能不会出现在所有浏览器中.所以我可能会做这样的事情:
Also remember bind has been introduced in ECMAScript 5, so it may not be present in all browsers. So I would probably do something like this instead:
click: function(){$root.setPath($data, $data.tierName(), $parent.identifier());}
这里是关于bind.
这篇关于将参数传递给knockoutjs viewmodel中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!