无法获取正确的淘汰绑定上下文

Unable to get correct knockout binding context

本文关键字:淘汰 绑定 上下文 获取      更新时间:2024-04-22

我有下面的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'

我试过对语法做一些修改,但似乎都做不好,哪里出了问题?

问题在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);
        } 
       })
    }]
};

考虑为视图模型使用构造函数,而不是对象文字;这使得处理范围问题更加容易和干净。请参阅此答案以获取示例。

通常在JavaScript中使用this不是最好的主意。尤其是淘汰赛。在执行过程中,您永远不知道this会是什么。

所以我建议这样写:

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模式的讨论。