Can you add a knockoutjs style binding by specifying a property + value together?

I have a question about style binding. Is it possible to generate all style binding text? So, ownership and value of 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()); 

A simple way is:

 <div data-bind="style: { fontSize: fontSize() + 'px'}"> <p>Lorem ipsum</p> </div> 

Is it possible to do it like this (I tried, this did not work):

 <div data-bind="style: { fontSizeCSS() }"> <p>Lorem ipsum</p> </div> 

If so, how? If not, why not? You can associate text with an html style element, but I was wondering if you can make this somewhat similar to what I suggest? Thanks!

+7
source share
1 answer

The main style binding parameter is not string , but

You should pass a JavaScript object in which the property names correspond to the style names and the values ​​correspond to the style values ​​that you want to apply.

So, your computed fontSizeCSS should return an object, not a string, and it will work fine:

 this.fontSizeCSS = ko.computed(function() { return {"fontSize": this.fontSize() + "px"}; }, this); 

JSFiddle demo.

+12
source share

All Articles