具有KnockoutJS属性的计算变量?

时间:2014-12-30 22:46:59

标签: knockout.js

计算变量可以具有属性吗?

例如,我有房间尺寸的用户输入,我希望它们通过一些缩放逻辑,屏幕上的其他内容需要读取。

当更新Width,Height或Depth时,我需要更新所有ScaledRoom W / H / D,因为这将是一个根据情况改变所有三个值的逻辑。

var MyViewModel = function () {
    var self = this;

    //Room Dimensions
    self.RoomWidth = ko.observable();
    self.RoomHeight = ko.observable();
    self.RoomDepth = ko.observable();


    //basic psuedocode of what I want to achieve... Haven't put in the previously mentioned logic in order to keep it simple
    self.ScaledRoom = ko.computed(function () {
        this.Width = self.RoomWidth * 10;
        this.Height = self.RoomHeight * 15;
        this.Depth = self.RoomDepth * 11;
        return this;
    });

};

在html中,我希望能够将数据绑定到ScaledRoom.Width(),例如

最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

为ScaledRoom创建单独的模型:

var ScaledRoom  = function () {
    var self = this;

    self.Width = ko.observable(0);
    self.Height = ko.observable(0);
    self.Depth = ko.observable(0);
}

然后你可以有一个计算的observable来改变对象的值。 if语句首先检查是否有对象。如果没有对象则创建它。

var ViewModel = function () {
    var self = this;

    self.RoomWidth = ko.observable(0);
    self.RoomHeight = ko.observable(0);
    self.RoomDepth = ko.observable(0);

    self.ScaledRoom = ko.computed(function () {
        var scaledRoom;
        if (!self.ScaledRoom) {
            scaledRoom = new ScaledRoom();
        }
        else {
            scaledRoom = self.ScaledRoom();
        }

        scaledRoom.Width(self.RoomWidth() * 10);
        scaledRoom.Height(self.RoomHeight() * 15);
        scaledRoom.Depth(self.RoomDepth() * 11);

        return scaledRoom;
    });
};

查看:

<div>
    Room Width: <input type="text" data-bind="value: RoomWidth"/>
</div>
<div>
    Room Height: <input type="text" data-bind="value: RoomHeight"/>
</div>
<div>
    Room Depth: <input type="text" data-bind="value: RoomDepth"/>
</div>
<div data-bind="with: ScaledRoom">
    <div data-bind="text: Width"></div>
    <div data-bind="text: Height"></div>
    <div data-bind="text: Depth"></div>
</div>

演示:http://jsfiddle.net/bmk3eo4m/