简体   繁体   中英

Knockout.js CSS Computed From Observables

I have two observables, one that specifies a module name and the other that sets a height for some of its children. I am trying to make a custom css computed observable that includes these two observables like so:

self.moduleId = ko.observable('dbm-name');
self.slideWidth = ko.observable(75);
self.css = ko.observable('');
self.setcss = ko.computed({
    read: function() {
        return '#' + self.moduleId() +
               ' {\n\tbackground: #fff;\n\tcolor: #000;\n}
                  \n.cont_width {\n\twidth: ' + self.slideWidth() +
               '%;\n}';
    },
    write: function(value) {
        self.css(value);
        return value;
    }
});

but it should also allow the user to manually write/edit some css. The problem is that once either moduleId or slideWidth is changed the css observable is not updated unless the user goes into the custom css textarea and makes a change (ie. add and remove a space just to get it to update). How can I automatically update the css observable when either of the other two observable values change? Or is there a better way of setting up my css functionality?

You can specify the read function to also set your css:

self.setcss = ko.computed({
        read: function() {
            var _css = '#' + self.moduleId() +
                '{\n\tbackground: #fff;\n\tcolor: #000;\n}' +
                '\n.cont_width {\n\twidth: ' + self.slideWidth() +
                '%;\n}';
            self.css(_css);       
        },
        write: self.css
 });

But like this you can only have one of the values as your css, either the user typed css or the computed product, at each moment in time.

But I suppose you could modify the read in such a way that it either concatenating the values to add the new one at the end of the css you already have.

here is a working fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM