4

我有一个自定义绑定用于格式化百分比数字。

ko.bindingHandlers.textPercent = {
    //init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
    //    //init logic 
    //},
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var val = parseFloat(ko.utils.unwrapObservable(valueAccessor()));
        if ($.isNumeric(val)) {
            $(element).text((val * 100).toFixed(2))+"%";
        }
        else {
            $(element).text("#Error");
        }
    }
}

用法:

<span data-bind="textPercent: amount" ></span>

<span data-bind="textPercent: amount()/2" ></span>

它工作正常,但我希望能够使用不同数量的固定数字,所以我做了一个扩展器:

ko.extenders.percent = function (target, precision) {
    var result = ko.computed({
        read: function () {
            return (target()*100).toFixed(precision)+"%";
        },
        write: function (newValue) {
            target(parseFloat(newValue) / 100);
        }
    });
    return result;
};

用法:

<span data-bind="text: amount.extend({ percent: 2 })" ></span>

<span data-bind="text: (amount()/2).extend({ percent: 2 })" ></span>

问题是它不适用于内联计算。

建议?

http://jsfiddle.net/eRapL/4/

4

1 回答 1

4

你必须用ko.observable()

例子:

text extend percent: <span data-bind="text: ko.observable(amount() / 2).extend({ percent: 2 })" ></span><br/>

看:http: //jsfiddle.net/c7Qx7/1/

于 2012-05-16T22:07:09.857 回答