【问题标题】:Determine if an item is the first item in an observableArray确定一个项目是否是 observableArray 中的第一个项目
【发布时间】:2014-08-09 05:17:55
【问题描述】:

我有一个模板,它绑定到一个淘汰赛 observableArray。我试图让一些东西只显示在数组中的第一个项目上。当第一个项目被删除时,成为第一个项目的下一个项目应显示此部分。它应该类似于以下代码。关键是 isFirst 函数。

HTML

<div data-bind="template: { name: 'my-template', foreach: people }"></div>
<script type="text/html" id="my-template">
    <div>
        <span data-bind="visible: isFirst">The first person is </span>
        <span data-bind="text: name"></span>
    </div>
</script>
<button data-bind="click: removeFirst">Remove First</button>

视图模型

function Person(p,name,age) {
   this.parent = p;
   this.name = name;
   this.age = age;
   this.isFirst = ko.computed(function(){
       return this.parent.people.indexOf(this) === 0;
   });
}
var viewModel = function() {
   var self = this;
   self.people = ko.observableArray();
   self.people.push(new Person(self, 'Fred', 25));
   self.people.push(new Person(self, 'Joe', 15));
   self.people.push(new Person(self, 'Sally', 21));
   self.people.push(new Person(self, 'Ann', 37));
   self.people.push(new Person(self, 'Jack', 52));

   self.removeFirst = function () {
          people.splice(0, 1);
      }
   };   
};

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    由于您在 foreach binding 的上下文中,您可以利用“注意 2:使用 $index、$parent 和其他上下文属性下的链接中详细介绍的 $index 属性>"

    你有几个不同的选择。

    1. 使用无容器 if binding 仅呈现第一个元素的标记,类似于此 question 中的讨论

      <!-- ko if: $index()=== 0 -->
       <span>The first person is</span>
      <!-- /ko -->
      
    2. 继续使用visible 绑定为每个元素呈现标记,但仅在第一项上可见

      <span data-bind="visible: $index() == 0">The first person is </span>
      

    对于这种特殊情况,选项 #1 是更合适的方法。


    编辑:将其保留在视图模型中:

    我会将isFirst 移动到$root,然后更改绑定。因为,我们已经有了$index,你可以把它传入

    <!-- ko if: $root.isFirst($index) -->
    

    -

     self.isFirst = function(index){
      return 0 === index();
    }
    

    与您原来的方法类似:

    <!-- ko if: $root.isFirst($data) -->
    

    -

    self.isFirst = function(item){
      return 0 === self.people.indexOf(item);
    }
    

    【讨论】:

    • 太好了,谢谢!你最初的反应比我预期的更容易、更整洁。但很高兴我问了,从未想过将 $Index() 传递给函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    相关资源
    最近更新 更多