Refresh masonry layout after knockoutJS databound template is inserted into a container

[亡魂溺海] 提交于 2020-01-15 06:05:08

问题


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?


回答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



来源:https://stackoverflow.com/questions/17331621/refresh-masonry-layout-after-knockoutjs-databound-template-is-inserted-into-a-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!