Knockoutjs formatCurrency函数在视图中不起作用

时间:2014-08-11 23:22:10

标签: knockout.js

http://knockoutjs.com/examples/cartEditor.html处的Knockoutjs购物车编辑器示例中复制formatCurrency函数,但无法使其在视图中工作,如示例所示。当我从视图模型中调用它时,它可以工作。我也能够复制货币绑定处理程序,这是有效的。我的视图和视图模型如下。

<span>Total salary: </span><span data-bind="text: totalSalary"></span><br />
<span>Total salary: </span><span data-bind="currency: totalSalary, symbol: '$'"></span><br />
<span>Total salary: </span><span data-bind="text: totalFormattedSalary"></span><br />
<span>Total salary: </span><span data-bind='text: formatCurrency(totalSalary)'></span>

并查看模型:

// from http://tech.pro/blog/1863/10-knockout-binding-handlers-i-don-t-want-to-live-without
ko.bindingHandlers.currency = {
    symbol: ko.observable('$'),
    update: function(element, valueAccessor, allBindingsAccessor){
    return ko.bindingHandlers.text.update(element,function(){
        var value = +(ko.utils.unwrapObservable(valueAccessor()) || 0),
        symbol = ko.utils.unwrapObservable(allBindingsAccessor().symbol === undefined
                ? allBindingsAccessor().symbol
                : ko.bindingHandlers.currency.symbol);
        return symbol + value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
    });
    }
};

function formatCurrency(value) {
    return "$" + value.toFixed(2);
};

var Teacher = function(id, name, salary) {
    this.id = id;
    this.name = name;
    this.salary = salary;
};

var viewModel = function(teachers) {
    var self = this;
    self.teachers = ko.observable(teachers);
    self.totalSalary = ko.computed(function() {
        var total = 0;
        $.each(self.teachers(), function() { total += this.salary; });
        return total;
    });
    self.totalFormattedSalary = ko.computed(function() {
        var total = 0;
        $.each(self.teachers(), function() { total += this.salary; });
        return formatCurrency(total);
    });
};

var initialTeachers = [
    new Teacher(1, "Tom", 40000),
    new Teacher(2, "Bill", 41000),
    new Teacher(3, "Bob", 42000)
];

var vm = new viewModel(initialTeachers);
ko.applyBindings(vm);

JSFiddle

TIA,史蒂夫

编辑:如果您在Chrome中点击了F12,则会返回错误:“未捕获的ReferenceError:无法处理绑定”text:function(){return formatCurrency(totalSalary)}“ 消息:formatCurrency未定义“它试图从视图中调用该函数的位置。如果删除视图中的最后一行,则没有错误。

1 个答案:

答案 0 :(得分:4)

totalSalary是一个可观察的。您必须通过将其作为函数

获取
formatCurrency(totalSalary())

http://jsfiddle.net/wape5ts8/31/

undefined is not a function来自.toFixed可观察的totalSalary,这是一个函数。