我如何构建正确的视图模型(与多个依赖关系)在KnockoutJS
How do I construct the proper view model (with multiple dependencies) in KnockoutJS?
下面是我使用的标记的一个子集:
<div id="item_one"></div>
<div id="item_two"></div>
<div id="item_three"></div>
<p id="result_one">0</p>
<p id="result_two">0</p>
<p id="result_three">0</p>
期望的行为是:
- 当您点击一个div时,p标签对应的文本将从0切换到1。
- p标签的文本将被连接成一个字符串,例如,单击第二个项目,结果字符串将是"010"。
- 有一个包含8个元素的数组,以二进制字符串作为键。当单击时,数组中选定的项会发生变化。
这似乎是一个很好的击倒,但我是一个完全的新手。如何设置适当的依赖项?
下面是一个示例:http://jsfiddle.net/rniemeyer/XqDsy/
为方便起见,我创建了一个小的"binaryObservable",它公开了一个toggle函数。
function binaryObservable(initialValue) {
var result = ko.observable(initialValue);
result.toggle = function() {
result(result() === "1" ? "0" : "1");
};
return result;
}
function ViewModel() {
this.one = binaryObservable("0");
this.two = binaryObservable("0");
this.three = binaryObservable("0");
this.combined = ko.dependentObservable(function() {
return this.one() + this.two() + this.three();
}, this);
this.choices = {
"000": { id: 0, value: "000" },
"001": { id: 1, value: "001" },
"010": { id: 2, value: "010" },
"011": { id: 3, value: "011" },
"100": { id: 4, value: "100" },
"101": { id: 5, value: "101" },
"110": { id: 6, value: "110" },
"111": { id: 7, value: "111" }
};
this.selectedChoice = ko.dependentObservable(function() {
var combined = this.combined();
return combined ? this.choices[combined] : {};
}, this);
}
ko.applyBindings(new ViewModel());
那么HTML可能看起来像:
<div id="item_one" data-bind="click: one.toggle">option one</div>
<div id="item_two" data-bind="click: two.toggle">option two</div>
<div id="item_three" data-bind="click: three.toggle">option three</div>
<hr/>
<p id="result_one" data-bind="text: one">0</p>
<p id="result_two" data-bind="text: two">0</p>
<p id="result_three" data-bind="text: three">0</p>
<hr/>
<p data-bind="text: combined"></p>
<hr/>
Selected choice: <span data-bind="text: selectedChoice().id"></span>
我远非专家,但像这样的东西?jsFiddle
相关文章:
- knockoutjs可观察数组
- KnockoutJS-组件-多个实例
- 从复选框和Selects-KnockoutJS中获取值的总和
- 气质的“nestRemoting()”有时可以'找不到关系
- 如何在Parse中创建一对多关系
- Ext.js从json构建模型关系的问题
- JSDoc:模块和名称空间之间的关系是什么
- 单元测试依赖关系没有被嘲笑
- 使用KnockoutJS绑定的YUI DataTable
- FRP 中 EventStreams 的循环依赖关系
- 节点模块依赖关系
- html5视频播放器和视频js之间的关系
- observablearray KnockoutJs中的对象
- 在foreach中加载所有项后,Knockoutjs组件回调
- KnockoutJS:为虚拟元素使用嵌套的条件if语句
- 如何从类关系中检索对象列表
- 用于多个选项卡和模块化的knockoutjs设计模式
- 在Meteor中使用具有依赖关系的NPM包
- 如何在knockoutjs中实现复选框依赖关系
- 我如何构建正确的视图模型(与多个依赖关系)在KnockoutJS