simonexmachina / jquery-bonsai

Super lightweight jQuery tree plugin
http://simonwade.me/jquery-bonsai
MIT License
148 stars 42 forks source link

Not working with Ajax #5

Closed renjithprince closed 9 years ago

renjithprince commented 9 years ago

Plugin is working with normal HTML. But im fetching the child nodes using ajax, In this case the plugin is not working. Is there any way to Fix this?

simonexmachina commented 9 years ago

This is definitely supported. You need to ensure that you're calling $('#foo').bonsai() after #foo has been populated. Version 1.0 also has an update method now, see the docs.

Can you post a JSBin showing your problem?

scompto commented 9 years ago

I am having the general plugin working, but the data object being passed through the onListItem event does not contain the id of the element from the JSON, or the name. This means I cannot data-bind it to the value of the checkbox. This is the case with your own example on http://aexmachina.github.io/jquery-bonsai/

simonexmachina commented 9 years ago

I'm not seeing any issues with that. Can you be more specific, or maybe create a JSBin that shows the problem.​

simonexmachina commented 9 years ago

Resolved by PR to jquery-json-list

joshuapinter commented 6 years ago

Hi @aexmachina and @scompto, I'm trying to get the child nodes being pulled in via AJAX when the parent node is expanded. Is there a good example for this or can you point me in the right direction?

Thanks!

(Great library, btw! 👍 )

simonexmachina commented 6 years ago

You'd want to subscribe to $('.tree input[type=checkbox]').on('change', loadChildren) and then do something like this:

function loadChildren() {
  $el = $(this)
  addChildNodes($el).then(() => $('.tree').bonsai('update'))
}
joshuapinter commented 6 years ago

@aexmachina Beautiful. Exactly what I needed. Thanks again!

joshuapinter commented 6 years ago

Just to help others, here is roughly how I accomplished this.

(In CoffeeScript.)

# Dynamically load child nodes when expanded.
$('li.parent.has-children > div.thumb').click( -> 
  $ul = $( @ ).siblings('ul')

  # I put a loading div inside as a placeholder. If there is no loader, it's already been loaded.
  already_loaded = ( $ul.find( ".loader" ).length == 0 ) 

  # Don't load again if already loaded.
  return if already_loaded

  $ul.load( $ul.data( 'url' ) )
)

It's important that you put at least one child <li> in order for Bonsai to know that there are children and show the expand arrow for users to click on. I used this child <li> as a loader placeholder.

<li>
  <div class="loader"></div>
</li>

Those are the key pieces. You can tweak and play with the rest as necessary.

simonexmachina commented 6 years ago

Better to go .on('change' so that it works with the keyboard too 👍