懒人用knockoutjs加载图片

时间:2014-06-25 17:03:03

标签: javascript knockout.js lazy-loading

我试图使用knockoutjs绑定延迟加载图像。 我能够懒惰加载图像没有knockoutjs框架,但我不知道我怎么能用knockoutjs绑定做到这一点。 这是我的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

1 个答案:

答案 0 :(得分: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