0
votes

i am using the Knockout js custom binding to bind some new div element inside the div,using class and i am getting data from database,its working only for single data,if the data is more than one,it again getting bind inside the same div like my below code,

 //for single data it working 
<div data-bind="foreach:items">
  <ul data-role="listview">
  <li>
     <div databind="BindingImage({img:imageurl})" class="Image">
        <div id="img1"><img src=1.png /></div>
     </div>
  </li>
  </ul>
</div>

//for multiple data it not  working 
<div data-bind="foreach:items">
  <ul data-role="listview">
  <li>
    <div databind="BindingImage({img:imageurl})"class="Image">
        <div class="imageWrapper" id="img1"><img src=1.png /></div>
        <div clas="imageWrapper" id="img2"><img src=2.png /></div>
   </div>
        for multiple data its create databind="BindingImage div, but inside the div it does not bind anything, i need to bind image2 in this div but its getting bind on first  div itself,i need to bind first image inside the first BindingImage div and next  one in another BindingImage div where i am doing wrong. 
   <div databind="BindingImage({img:imageurl})"class="Image"></div>
  </li>
  </ul>
</div>


//custom binding//
ko.bindingHandlers.BindingImage = { 
    update: function(element, valueAccessor) {
        id+=1
        var className = element.className;
        imagewrapper= document.createElement('div');
        imagewrapper.className = "imageWrapper";
        imagewrapper.id = "img1"+id
        document.querySelector("." +className).appendChild(imagewrapper)
    }
};
1
You Html is messy, Lots of ending tags are missing. - Samir
databind="BindingImage({img:imageurl})" is anything, but it's definitely not knockout binding syntax. Contrary to what you say I'm pretty sure that this code does not work at all. - Tomalak

1 Answers

0
votes

There are 2 major issues:

  • First, id=+1. This will always return 1. This is same as i= parseInt(1). It should be id+=1
  • Second document.querySelector("." +className).appendChild(imagewrapper), this will always append to 1st container. Replace it with element.append() or document.querySelectorAll("." +className)[id-1].appendChild(imagewrapper), considering id will start with 1.

You are also missing closing tags for ul