Knockout - 为输入和样式编写不同的观察值

时间:2017-10-12 09:23:54

标签: knockout.js

一个可观察的整数,用于存储用于css变量的值,如widthheight。为了在css中正确应用,这些变量需要一个额外的单位,例如pxmm。但是,在我的viewmodel中,我想存储纯整数,并希望能够在输入字段中更改它。

我现在需要的是一种告诉敲门的方法,无论何时将此值插入style - 绑定,都必须使用相应的单位字符串(px)进行扩充。

https://jsfiddle.net/nfyosayr/2/

2 个答案:

答案 0 :(得分:1)

Here是一个工作小提琴。只需更新后备可观察对象(mywidth):

<input type="number" data-bind="textInput : mywidth" />

计算结果应该是只读的:

this.myfullwidth = ko.computed(function() {
  return self.mywidth() + 'px';
});

最后,将结果值应用于div:

<div id="my-div" style='background-color:red' data-bind="style : { width : myfullwidth }">
  this is my div
</div>

替代解决方案:

你可以看看this小提琴。您还可以绑定到后台可观察对象,并在标记中添加px后缀。但是,请确保在这种情况下,您需要在HTML中应用一组括号()

data-bind="style : { width : mywidth() + 'px' }"

答案 1 :(得分:0)

我终于用自定义绑定解决了它:

   ko.bindingHandlers.style_extended = {
                init: function(element,valueAccessor,allBindingsAccessor,box) {

                    var obj = valueAccessor();
                    for(let index in obj) {
                        if (index != 'unit') {
                            element.style[index] = obj[index]()+obj['unit'];
                        }
                    }
                },
                update: function(element,valueAccessor,allBindingsAccessor,box) {

                    var obj = valueAccessor();
                    for(let index in obj) {
                        if (index != 'unit') {
                            element.style[index] = obj[index]()+obj['unit'];
                        }
                    }
                }
            };

<div style='background-color:red' data-bind="style_extended : { width : mywidth }">
  this is my div
</div>