繁体   English   中英

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

[英]Unable to get correct knockout binding context

我有以下执行我的剔除绑定的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'

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

通常它是不使用最好的主意, this在JavaScript中。 尤其是淘汰赛。 你永远不知道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模式的讨论

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

考虑为视图模型使用构造函数,而不是对象文字。 这使得处理范围问题变得更加容易和清洁。 有关示例,请参见此答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM