2

I have a knockout template binding used to bind list of divs to an observable array:

<div class="menu-instance-entries js-masonry" data-masonry-options='{ "gutter": 20, "itemSelector": ".menu-entry" }' data-bind="template: { name: 'menu-entries-template', foreach: MenuEntries }"></div>

MenuEntries is an observable array that gets a new element "pushed" into it by a click handler bound to a view model's function.

The layout of the elements in the .menu-instance-entries container is controlled by the masonry plugin and in order for the manual absolute positioning to take place, one need to call $container.masonry( 'prepended', elements ) passing the elements collection.

I am in control at the point of where observable collections' .push occures, but I have no idea how to get a jQuery element from a newly created div by template to pass onto a jQuery call to masonry plugin.

What should I do to have the layout updated on knockout element adding via observable array?

Maxim V. Pavlov
  • 10,303
  • 17
  • 74
  • 174

1 Answers1

1

You can use the afterAdd or beforeRemove functions of the template binding, I advice against it though because you get dependencies to the DOM from the ViewModel.

Better to create a custom binding that handles the interaction between masonry and KO

Anders
  • 17,306
  • 10
  • 76
  • 144
  • I like this suggestion, and the reasoning behind it. However I'm falling a bit short on implementation. I followed an example given [here](http://stackoverflow.com/questions/11031719/bindinghandler-in-knockoutjs-build-own-listview), with some tweaks of course. Where in the update method would I adjust layout to resize appropriately. – BigDubb Oct 31 '13 at 03:27