13

I have the following code:

// First we define our gift class, which has 2 properties:
// a Title and a Price.
// We use knockout js validation to ensure that the values input are suitable/ 
function Gift(item)
{
    var self = this;
    self.Title = ko.observable(item.Title);

    // attach some validation to the Title property courtesy of knockout js validation
    self.Title.extend({
        required: true,
        minLength: 3,
        pattern: {
            message: 'At least ',
            params: '^[a-zA-Z]+\s?[a-zA-Z]*'
        }
    });
    self.Price = ko.observable(item.Price);
    self.Price.extend({required:true,number:true,min:0.1,max:1000});
};


var viewModelForTemplated =
{
    gifts: ko.observableArray(),        // gifts will be an array of Gift classes

    addGift: function ()
    {
        this.gifts.push(new Gift({ Title: "", Price: "" }));
    },
    removeGift: function (gift)
    {
        this.gifts.remove(gift);
    },

    totalCost: ko.computed(function () {
        if (typeof gifts == 'undefined')
            return 0;

        var total = 0;

        for (var i = 0; i < gifts().length; i++)
        {
            total += parseFloat(gifts()[i].Price());
        };
        return total;
    })
}


$(document).ready(function ()
{
    // load in the data from our MVC controller 
    $.getJSON("gift/getdata", function (allGifts)
    {
        var mappedgifts = $.map(allGifts, function (gift)
        {
            return new Gift(gift);
        });

        viewModelForTemplated.gifts(mappedgifts);
    });

    ko.applyBindings(viewModelForTemplated, $('#templated')[0]);
}

and then (above the script)

<div id="templated">

<table >
    <tbody data-bind="template: { name: 'giftRowTemplate', foreach: gifts }"></tbody>
</table>

<script type="text/html" id="giftRowTemplate">
    <tr>
        <td>Gift name: <input data-bind="value: Title"/></td>
        <td>Price: \$ <input data-bind="value: Price"/></td>           
        <td><a href="#" data-bind="click: function() { viewModelForTemplated.removeGift($data) }">Delete</a></td>
    </tr>
</script>

<p>Total Cost <span data-bind="text: totalCost"></span> </p>    

<button data-bind="click: addGift">Add Gift</button> 

<button data-bind="click: save">Save</button>

</div>

The totalCost method only runs once, when the gifts array is empty, and I can push or remove items onto the observableArray() no problem but nothing fires .

How do I get the span referring to totalCost to update? I bet it's something simple :)

Thanks for your help.

4

2 回答 2

12

你需要解开你的 observable:

totalCost: ko.computed(function () {
    //also, you forgot typeof below
    if (typeof gifts == 'undefined')
       return 0;

    var total = 0;  //here \/
    for (var i=0; i < gifts().length; i++)
    {                //and here  \/
        total += parseFloat(gifts()[i].Price());
    };
    return total;
})

它不更新的原因是因为

gifts.length

始终评估为0,并且从不进入循环。即便如此,

gifts[i].Price()

出于同样的原因不会工作;你需要解开可观察的。


请注意,当您不展开它时,长度计算为零的原因是因为您获得了实际可观察​​数组函数的长度。Knockout 中的所有 observables 都作为常规函数实现;当你不打开它时,你会碰到实际的函数本身,而不是底层数组。


编辑,

此外,您需要使用 引用礼物this.gifts,因为它是一个对象属性。这就是为什么这不起作用。礼物总是不确定的。

也就是说,您还需要做更多的工作才能让 ko 计算从对象字面量中工作。在这里阅读更多信息:

http://dpruna.blogspot.com/2013/09/how-to-use-kocomputed-in-javascript.html

以下是我将如何制作您的视图模型:

function Vm{
    this.gifts = ko.observableArray();        // gifts will be an array of Gift classes

    this.addGift = function () {
        this.gifts.push(new Gift({ Title: "", Price: "" }));
    };

    this.removeGift = function (gift)
    {
        this.gifts.remove(gift);
    };

    this.totalCost = ko.computed(function () {
        var total = 0;

        for (var i = 0; i < this.gifts().length; i++)
        {
            total += parseFloat(this.gifts()[i].Price());
        };
        return total;
    }, this);
}

var viewModelForTemplated = new Vm();
于 2013-10-28T16:30:04.160 回答
0

在将索引器应用于它时,您必须observableArray使用展开()。更新totalCost如下:

totalCost: ko.computed(function () {
    if (this.gifts == 'undefined')
       return 0;

    var total = 0;
    for (var i=0; i<this.gifts().length;i++)
    {
        total += parseFloat(this.gifts()[i].Price());
    };
    return total;
})
于 2013-10-28T16:30:32.767 回答