2014-06-25 86 views
2

我想懒惰加载与knockoutjs绑定的图像。 我能够在没有knockoutjs框架的情况下延迟加载图像,但我不知道如何使用knockoutjs绑定来做到这一点。 这里是我的HTML懒惰加载图像与knockoutjs

 <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

+1

哪里延迟加载实现的?我只是看到具有普通'src'属性的图像。 – pixelistik

+0

你想要加载图像的时间? – TrueEddie

回答

1

我已通过的foreach之前添加额外的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

+0

如果这不是您正在寻找的解决方案,请删除此答案并使用新代码更新问题。使用帖子下方的“编辑”链接。 – brasofilo

+1

是的,我已经更新了我的答案,我正在寻找。这可能有助于某人。 – Jai