Reputation: 19700
So there is a new binding pre-processing feature shipped with the latest Knockout. It says that along with init
and update
methods a binding can have a preprocess
method that takes a value
, name
, and an addBinding
callback. It's all nice and neat, but
value
and name
being parsed? are they just split by a comma?value
from the binding string?EDIT
As we know a binding string can contain more than one binding expression. So how does KO know when one expression ends and another one begins? We could assume the binding expression is expected to be a valid key-value pair separated by comma and having a valid javascript expression on the right side however it's not the case as example #1 from documentation shows. Well if it is something different than that what is it?
Upvotes: 2
Views: 1246
Reputation: 16688
When a binding string contains more than one binding, the bindings are separated by a comma. Thus a, b
is interpreted as two bindings, a
, and b
. Within each binding, the name and value are separated by a colon. Thus a: b
is a single binding with the name a
and value b
. If no colon is present, the value of the binding is undefined
.
The name can be specified as a string, in which case it may contain any character except a quote: 'some crazy binding :-)': true
. Without quotes, it may contain any character except the following ,:/'"()[]{}
.
The value can be any valid JavaScript expression, as long there are no top level commas. It may also be any value as long as quotes and opening parentheses, brackets, and braces are matched and there are no top-level commas. For example, if your binding was a: happy :-)
, the value provided to preprocess
would be happy:-)
(spaces are not considered important around operator characters). If it's not valid JavaScript, though, it must be converted to valid JavaScript by the preprocess
function.
Upvotes: 1
Reputation: 139758
You get the value
and name
as strings which containing exactly the text what you have written in your binding in the view so no parsing is involved.
From the documentation:
value
: the syntax associated with the binding value before Knockout attempts to parse it (e.g., for yourBinding: 1 + 1, the associated value is "1 + 1" as a string).
name
: the name of the binding (e.g., for yourBinding: 1 + 1, the name is "yourBinding" as a string).
You can easiliy create a simple example with :
ko.bindingHandlers.myFancyBinding = {
preprocess: function (value, name, addBindingCallback) {
console.log(value);
console.log(name);
return value;
}
}
And if you use it like this:
<div data-bind="myFancyBinding: 1+2+'some crazy expresssion'"></div>
The output will be:
1+2+'some crazy expresssion'
myFancyBinding
Demo JSFiddle.
Upvotes: 2