【问题标题】:How do I construct the proper view model (with multiple dependencies) in KnockoutJS?如何在 KnockoutJS 中构建正确的视图模型(具有多个依赖项)?
【发布时间】:2011-12-28 08:44:48
【问题描述】:

这是我正在使用的标记的一个子集:

<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>

期望的行为是:

  1. 当你点击一个div时,p标签对应的文本会从0切换到1。
  2. p 标签的文本将被连接成一个字符串,例如,单击第二个项目,结果字符串将是“010”。
  3. 有一个包含八项的数组,以二进制字符串为键。进行点击时,数组中的选定项会发生变化。

这似乎是淘汰赛的一个很好的用途,但我是一个完全的菜鸟。如何设置正确的依赖项?

【问题讨论】:

    标签: javascript mvvm knockout.js


    【解决方案1】:

    以下是一种方法的示例:http://jsfiddle.net/rniemeyer/XqDsy/

    为方便起见,我创建了一个小“binaryObservable”,它公开了一个切换功能。

    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>
    

    【讨论】:

      【解决方案2】:

      我远非专家,但像这样? jsFiddle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-24
        • 1970-01-01
        • 2013-05-11
        • 2018-09-08
        • 2016-08-11
        相关资源
        最近更新 更多