I have a question regarding the style binding. Is it possible to generate the whole style binding text? So the property and value parts together? For example:
function ViewModel() {
this.fontSize = ko.observable(12);
this.fontSizeCSS = ko.computed(function() {
return "font-size: " + " " + this.fontSize() + "px";
}, this);
}
// Activates knockout.js
ko.applyBindings(new ViewModel());
The the simple way is to do like this:
<div data-bind="style: { fontSize: fontSize() + 'px'}">
<p>Lorem ipsum</p>
</div>
Is it possible to do it a way like this( I tried, it did not work):
<div data-bind="style: { fontSizeCSS() }">
<p>Lorem ipsum</p>
</div>
If yes, how? If not, why not? One can do a text binding to a html style element, but I was wondering if you can do it somewhat similar, what I am proposing? Thanks!
KnockoutJS - Value Binding. This binding is used to link respective DOM element's value into ViewModel property. Mostly, this is used with elements such as input, select, and textarea. This is similar to text binding, the difference being, in value binding data can be changed by the user and the ViewModel will update it automatically.
This is a custom Knockout attribute (all custom HTML5 attributes have the data- prefix) that defines what attributes on the HTML element should bind to what properties on your binding context (we’ll see that in a minute). The binding then makes sure that any changes in your form are reflected in your data and vice versa.
You can even nest options within <optgroup> elements and Knockout will set the selected value appropriately. Normally, when you use the value binding on a <select> element, it means that you want the associated model value to describe which item in the <select> is selected.
Knockout has special support for drop-down lists (i.e., <select> elements). The value binding works in conjunction with the options binding to let you read and write values that are arbitrary JavaScript objects, not just string values. This is very useful if you want to let the user select from a set of model objects.
The main parameter of the style
binding is not a string
, but
You should pass a JavaScript object in which the property names correspond to style names, and the values correspond to the style values you wish to apply.
So your fontSizeCSS
computed should return an object and not a string, and it will work fine:
this.fontSizeCSS = ko.computed(function() {
return {"fontSize": this.fontSize() + "px"};
}, this);
Demo JSFiddle.
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