将参数传递给Knockout.js 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);
},
...........
...........
}
结果是一些敲除js核心代码显示在警报消息中(可能是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(),标识符是compute()
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
本身是可观察的(不清楚它是否来自您的代码),那么您也需要调用它:
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 .
这篇关于将参数传递给Knockout.js ViewModel中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!