javascript - 使用 knockoutjs 延迟加载图像

标签 javascript knockout.js lazy-loading

我正在尝试使用 knockoutjs 绑定(bind)延迟加载图像。 我能够在没有 knockoutjs 框架的情况下延迟加载图像,但我不确定如何使用 knockoutjs 绑定(bind)来做到这一点。 这是我的 HTML

     <div class='liveExample'> 
        <div class="row">
           <div data-bind="foreach: items">
              <div class="col-lg-4 col-md-4 col-sm-4 " style="padding: 0px">
                 <img data-bind=" attr: { src: $data }" class="lazy" />
              </div>
           </div>
       </div>
    </div>

Javascript:

var SimpleListModel = function(items) {
    this.items = ko.observableArray(items);
    bind(this);  // Ensure that "this" is always this view model
};

var pictures = []; //Initialise an empty array

for (var i = 0; i = 10 ; i++) {
    var image; //This is a placeholder
    image = 'http://dummyimage.com/300x200/000/fff&text=' + i; //Set the src attribute     (imageFiles[i] is the current filename in the loop)
    pictures.push(image); //Append the new image into the pictures array
}

ko.applyBindings(new SimpleListModel(pictures));

这是 jsfiddle

最佳答案

我通过在 foreach 绑定(bind)之前添加额外的 div 标签并将 afterrender 事件分配给父 div 使其工作

   <div class="row">
      <div data-bind='template: {afterRender: myPostProcessingLogic }'> 
<div data-bind="foreach: {data: items} ">
    <div class="col-lg-4 col-md-4 col-sm-4 " style="padding: 0px">
       <img data-bind=" attr: { 'data-original': $data }" class="lazy" style="min-width:100px; min-height:50px;"  />
    </div>
</div>
   </div>

</div>

Javascript

var SimpleListModel = function(items) {
this.items = ko.observableArray(items);
   this.myPostProcessingLogic = function(elements) {
        $("img.lazy").lazyload({
         effect: "fadeIn",
         effectspeed: 2000
       });
   }
};

var pictures = []; //Initialise an empty array
for (var i = 1; i < 100 ; i++) {
    var imageUrl = 'http://dummyimage.com/300x200/000/fff&text=' + i; //Set the image url
    pictures.push(imageUrl); //Append the new image into the pictures array
}
ko.applyBindings(new SimpleListModel(pictures));

这是 jsfiddle

关于javascript - 使用 knockoutjs 延迟加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24414616/

相关文章:

Angular 2 延迟加载 : RangeError: Maximum call stack size exceeded

javascript - Breeze.js 使用 noTracking 不展开实体

c# - 强制创建惰性对象

javascript - 如何放入将从另一台服务器加载数据的 HTML 代码?

javascript - jQuery - 悬停不适用于 for 循环

javascript - Vue - 包装 HTML5 元素

javascript - 使用高阶函数合并相等的对象

javascript - Knockout + Select2——设置默认值?

node.js - 在服务器端使用 node.js + express.js 在 SPA(单页应用程序)中动态生成内容的 SEO

Python 3 可迭代惰性 block 获取