Javascript 无法获取正确的敲除绑定上下文

Javascript 无法获取正确的敲除绑定上下文,javascript,knockout.js,Javascript,Knockout.js,我有以下javascript来完成我的敲除绑定 var context = this; var viewModel = { lineitems: [{ quantity: ko.observable(1), title: 'bar', description: 'foo', price: ko.observable(10), total: ko.observable(10), formatt

我有以下javascript来完成我的敲除绑定

var context = this;

var viewModel = {
    lineitems: [{
        quantity: ko.observable(1),
        title: 'bar',
        description: 'foo',
        price: ko.observable(10),
        total: ko.observable(10),
        formattedTotal: ko.computed({
        read: function () { 
            return '$' + this.price().toFixed(2);
        },
        write: function (value) { 
            value = parseFloat(value.replace(/[^\.\d]/g, ""));
            this.price(isNaN(value) ? 0 : value);
        } 
       })
    }]
};

ko.applyBindings(viewModel);
但是,当我应用formattedTotal时,我得到以下javascript错误

Uncaught TypeError: Object [object global] has no method 'price'

我尝试过对语法进行一些更改,但似乎无法正确执行,哪里出了问题?

通常在JavaScript中使用
这个
不是一个好主意。尤其是淘汰赛。您永远不知道在执行过程中此
将是什么

所以我建议这样写:

function LineItem(_quantity, _title, _description, _price) {
    var self = this;

    self.quantity = ko.observable(_quantity);
    self.title = ko.observable(_title);
    self.description = ko.observable(_description);
    self.price = ko.observable(_price);

    self.total = ko.computed(function () {
        return self.price() * self.quantity();
    }, self);

    self.formattedTotal = ko.computed(function () {
        return '$' + self.total().toFixed(2);
    }, self);
};

var viewModel = {
    lineItems: [
    new LineItem(10, 'Some Item', 'Some description', 200),
    new LineItem(5, 'Something else', 'Some other desc', 100)
]
};

ko.applyBindings(viewModel);

您可以阅读一些关于
self=this
模式的讨论

问题在
formattedTotal
方法中:范围-
this
-不是您的viewModel。试试这个:

var viewModel = {
    lineitems: [{
        quantity: ko.observable(1),
        title: 'bar',
        description: 'foo',
        price: ko.observable(10),
        total: ko.observable(10),
        formattedTotal: ko.computed({
        read: function () { 
            return '$' + viewModel.lineitems.price().toFixed(2);
        },
        write: function (value) { 
            value = parseFloat(value.replace(/[^\.\d]/g, ""));
            viewModel.lineitems.price(isNaN(value) ? 0 : value);
        } 
       })
    }]
};

考虑对viewmodels使用构造函数,而不是对象文本;这使得处理范围问题更容易、更清晰。例如,请参阅。

您确定这是正确的小提琴吗?完全是错误的。谢谢