从绑定中剔除 2.0 参数的顺序不正确?
Knockout 2.0 使用此数据绑定:
data-bind="click: $root.deleteSomeEntity.bind($data, $parent)"
在 Knockout 视图模型 JavaScript 中,第一个参数
self.deleteSomeEntity = function (data, parent) {
// perform deletion
}
似乎是父级而不是数据。
这种行为有原因还是我缺少什么?
With Knockout 2.0 using this data-bind:
data-bind="click: $root.deleteSomeEntity.bind($data, $parent)"
in the Knockout viewmodel JavaScript the first argument in
self.deleteSomeEntity = function (data, parent) {
// perform deletion
}
seems to be the parent rather than the data.
Is there a reason for this behavior or something I'm missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您调用
bind
时,第一个参数将是this
的值。因此,在您的调用中,this
将是$data
,第一个参数将是$parent
。如果在这种情况下
$root
是$parent
,那么你可以这样做:$root.deleteSomeEntity.bind($root)
KO 将通过数据作为第一个参数,
this
将设置为$root
。如果
$parent
不是$root
(并且您可能不想依赖于this
是与$root 不同的对象
在你的 root 方法中),那么你会做类似的事情:$root.deleteSomeEntity.bind($root, $data, $parent)
否则,肯定有方法来确保您的视图模型中有正确的
this
。但这取决于你的结构。When you call
bind
the first parameter will be the value ofthis
. So, in your callthis
will be$data
and the first argument will be$parent
.If
$root
is$parent
in this case, then you can just do:$root.deleteSomeEntity.bind($root)
KO will pass the data as the first parameter and
this
will be set to$root
.If
$parent
is not$root
(and you likely don't want to rely onthis
being a different object that$root
in your method on root), then you would do something like:$root.deleteSomeEntity.bind($root, $data, $parent)
Otherwise, there are certainly ways to make sure that you have the proper
this
within your view model. It depends on your structure though.为什么使用
bind()
?默认情况下,如果您只将 javascript 函数的名称写入单击事件,Knockout 将传递$data
作为第一个参数,将事件作为第二个参数。http://knockoutjs.com/documentation/click-binding.html(注 1& 2)
当你可以简单地做到这一点时,为什么还要费心使用
bind()
:Why are you using
bind()
? By default, if you just write the name of the javascript function as the click event Knockout will pass$data
as the first argument and the event as the second.http://knockoutjs.com/documentation/click-binding.html (Note 1&2)
Why bother with
bind()
when you can simply do this: