Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout 2.0 parameters from bind in incorrect order?

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?

like image 645
kendaleiv Avatar asked Feb 16 '12 14:02

kendaleiv


People also ask

What is binding in knockout?

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.

What is two way binding in knockout JS?

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.

What is $root in knockout?

$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.

Can we have multiple knockout models on a single page?

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.


2 Answers

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.

like image 92
RP Niemeyer Avatar answered Oct 02 '22 14:10

RP Niemeyer


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)}"
like image 44
soniiic Avatar answered Oct 02 '22 12:10

soniiic