无法从选择值绑定中读取属性

时间:2013-07-09 17:35:58

标签: knockout.js

我有一个选择,并且我试图在选择被更改时显示属性(当选择捐赠类型时,我想显示更多冗长的捐赠类型描述)。不幸的是,它不起作用;我看不到访问视图模型的selectedDonation属性的属性。

我有a fiddle这应该有助于说明我正在尝试做什么。这是我第一次将knockout.js纳入项目的实际尝试,请原谅初学者的错误。

我的选择如下:

<select data-bind="options: availableDonationTypes, optionsCaption: 'Please select...', value: selectedDonation.donationType, optionsText: 'label'"></select>

我试图在这里显示描述,但三元表达式总是评估为false。我做错了什么?

<span data-bind="text: selectedDonation() ? selectedDonation().donationType().description : 'No type selected'"></span>

如果我使用selectedDonation而不是selectedDonation()作为测试,表达式的计算结果为true,但我仍然无法找到访问所选捐赠类型描述的方法。

我的viewmodel和object:

function Donation(donationType, donationAmount) {
    var self = this;
    self.donationAmount = donationAmount;
    self.donationType = ko.observable(donationType);

    self.formattedAmount = ko.computed(function () {
        var amount = self.donationAmount;
        return amount ? "$" + amount.toFixed(2) : "None";
    });
}

function DonationsViewModel() {
    var self = this;

    self.availableDonationTypes = [{
        label: "Donation 1",
        description: "This is donation number 1."
    }, {
        label: "Donation 2",
        description: "This is donation number 2."
    }];

    self.selectedDonation = ko.observable();

    self.donations = ko.observableArray([
    new Donation(self.availableDonationTypes[0], 50),
    new Donation(self.availableDonationTypes[1], 75)]);

    self.totalDonation = ko.computed(function () {
        var total = 0;
        for (var i = 0; i < self.donations().length; i++)
        total += self.donations()[i].donationAmount;
        return total;
    });

    self.addDonation = function (form) {
        self.donations.push(new Donation(self.selectedDonation.donationType, parseInt(self.selectedDonation.donationAmount)));
    }
    self.removeDonation = function (donation) {
        self.donations.remove(donation);
    }
}

1 个答案:

答案 0 :(得分:1)

你的问题是selectedDonation一无所有。您无法将下拉列表的值绑定到dontationTypee property of nothing: it doesn't have such a property. selectedDonation needs to be a捐赠`对象。

以下是使用该方法的最后小提琴:http://jsfiddle.net/xUn9N/3/