Lets say I have a bound span
<span data-bind="MyBinding: Name"></span>
And I have a custom binding
ko.bindingHandlers.MyBinding = {
init: function (element, valueAccessor, allBindings, viewModel, context) {
// I want to get the string "Name" here. NOT the value of Name.
},
};
How do i get a string with the value of the binding expression inside the handler? ie how do i get "Name" not "Value of name".
I also need the expression so passing the string "Name" is not feasible.
<span data-bind="MyBinding: 'Name'"></span>
A binding context is an object that holds data that you can reference from your bindings. While applying bindings, Knockout automatically creates and manages a hierarchy of binding contexts. The root level of the hierarchy refers to the viewModel parameter you supplied to ko. applyBindings(viewModel) .
unwrapObservable(item) Looking at the code, that call basically checks to see if item is an observable. If it is, return the value(), if it's not, just return the value.
Binding Values The binding value can be a single value, literal, a variable or can be a JavaScript expression.
Actually, Knockout does have a built-in way to do this. You do need to adapt your custom binding a little (namely, it becomes an object instead of a string value). Knockout allows you, along with the init
and update
properties, to specify a preprocess
property. For example, suppose we have the following viewModel:
var app = { data: ko.observable('Hello World') };
And a simple binding that would convert the string passed to it fully to lowercase, and output both the binding's name and value (the property passed in the view obviously being data
):
ko.bindingHandlers.lower = {
update: function(elem, value) {
var obj = ko.unwrap(value());
elem.textContent = 'Name: ' + ko.unwrap(obj.name) +
' - Value: ' + ko.unwrap(obj.data).toLowerCase();
},
preprocess: function(value, bindingName) {
return '{data:' + value + ', name:\'' + bindingName + '\'}';
}
};
It's as simple as stringifying the value
property passed to it & transforming the binding's value into an object with 2 keys (name & value here). Have a look. See Binding preprocessing for more info.
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