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?
A binding consists of two items, the binding name and value, separated by a colon. Here is an example of a single, simple binding: Today's message is: <span data-bind= "text: myMessage" ></span> An element can include multiple bindings (related or unrelated), with each binding separated by a comma.
KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.
$root. This is the main view model object in the root context, i.e., the topmost parent context. It's usually the object that was passed to ko. applyBindings . It is equivalent to $parents[$parents.
Binding Multiple ViewModels Whether you are simply looking to keep your ViewModels nice and clean, or you have a shared ViewModel that appears on each page, there will come a time when you wish to bind multiple ViewModels on a single page. Knockout makes this quite easy.
When you call bind the first parameter will be the value of this. So, in your call this 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 on this 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.
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:
data-bind="click: function() {$root.deleteSomeEntity($data, $parent)}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With