在自定义绑定中Knockout ObservableArray

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在自定义绑定中Knockout ObservableArray相关的知识,希望对你有一定的参考价值。

我可以在自定义绑定中的init块中创建observableArray吗?另外,我想使用这个observableArray内部更新方法来推送一些新元素。

它循环例如:

    ko.bindingHandlers.yourBindingName = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        var animateImageArray = ko.observableArray(["img1", "img2"]);
        ko.applyBindings(animateImageArray);
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        //Also can I get a reference to animateImageArray here
    }
};

html

    <div class="customized-slider-wrapper" data-bind="yourBindingName: someData">
    <div class="customized-slider" data-bind="foreach: animateImageArray">
    <div class="individual-tile">
        <img data-bind= "attr: {src: $data}" />
    </div>
    </div>
</div>

编辑:

在评论中尝试了以下代码

      StopAnimation = setInterval(function () {

        _index++;
        if (_index >= imgArray.length) {
          _index = 0;
        }


         $(temp[_index]).attr('src', imgArray[_index]);


        toBeScrolledBy = slideWidth * _index;
        $(scroller).css({
          'transform': 'translateX(-' + toBeScrolledBy + 'px)'
        });

      }, 1500);

现在图像动画的序列出错了。第一个图像滑动和第二个加载,动画返回到第一个而不是第三个,并且每次在图像src数组中传递新索引时都会发生。

答案

根据您的描述,init不应该创建数组,并且数组可能不必是可观察的。相反,您的可观察产品数组将包含对象,并且每个产品对象将具有其图像的数组(可能不必是可观察的)。粗略草图:

var vm = {
  products: ko.observableArray([
      {
          name: "Widget",
          images: [
              "https://via.placeholder.com/100/5d5/fff.png?text=Widget+1",
              "https://via.placeholder.com/100/d55/fff.png?text=Widget+2",
              "https://via.placeholder.com/100/55d/fff.png?text=Widget+3"
          ]
      },
      {
          name: "Gadget",
          images: [
              "https://via.placeholder.com/100/55d/fff.png?text=Gadget+1",
              "https://via.placeholder.com/100/5d5/fff.png?text=Gadget+2",
              "https://via.placeholder.com/100/d55/fff.png?text=Gadget+3",
              "https://via.placeholder.com/100/55d/fff.png?text=Gadget+4",
              "https://via.placeholder.com/100/5d5/fff.png?text=Gadget+5"
          ]
      },
  ])
};

ko.bindingHandlers.productSlides = {
    init: function(element, valueAccessor) {
      // Current timer handle
      var timer = 0;
      // Current slide index
      var index = 0;

      // Show first slide
      element.src = ko.unwrap(valueAccessor())[index];

      // Set up handlers
      element.addEventListener("mouseenter", startTimer);
      element.addEventListener("mouseleave", clearTimer);
  
      // Show next slide
      function nextSlide() {
          // Re-read the observable in case it's changed
          var slides = ko.unwrap(valueAccessor());
          index = (index + 1) % slides.length;
          element.src = slides[index];
      }
  
      // Start showing slides
      function startTimer() {
        if (!timer) {
            nextSlide();
            timer = setInterval(nextSlide, 1000);
        }
      }
      
      // Stop showing slides
      function clearTimer() {
          if (timer) {
              clearInterval(timer);
              timer = 0;
          }
      }
      
      // Clean up on disposal
      ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
          element.removeEventListener("mouseenter", startTimer);
          element.removeEventListener("mouseleave", clearTimer);
          clearTimer();
      });
    }
};

console.log("Showing products");
ko.applyBindings(vm, document.body);

// Example of adding another product to the array later
setTimeout(function() {
    console.log("Adding third product");
    vm.products.push({
        name: "Doogle",
        images: [
            "https://via.placeholder.com/100/d55/fff.png?text=Doogle+1",
            "https://via.placeholder.com/100/5d5/fff.png?text=Doogle+2",
            "https://via.placeholder.com/100/55d/fff.png?text=Doogle+3",
            "https://via.placeholder.com/100/d55/fff.png?text=Doogle+4"
        ]
    });
}, 2000);
<div data-bind="foreach: products">
  <img data-bind="productSlides: images">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

以上是关于在自定义绑定中Knockout ObservableArray的主要内容,如果未能解决你的问题,请参考以下文章

Knockout自定义绑定数据

Knockout 创建自定义绑定

KnockoutJS 3.X API 第五章 高级应用 使用预处理扩展Knockout绑定语法

强制 Durandal 页面中的 Knockout 组件在绑定之前等待 Ajax 调用

Knockout自定义绑定更新无法正常工作

Knockout双向绑定