Skip to content

Instantly share code, notes, and snippets.

@Prinzhorn Prinzhorn/
Last active Nov 5, 2016

What would you like to do?
Conditional rendering handler for Epoxy.js

Similar to the toggle handler, but it will detach the element from the DOM instead of just hiding it. Much like knockout's if binding.


<div data-bind="if: someCondition"></div>

where someCondition can of course also be a computed property, so this gives you all flexibility you need.

Why not use just toggle? Because selectors like :first etc. won't work.

Backbone.Epoxy.binding.addHandler('if', function($element, value) {
var isDetached = $element[0].parentNode === null;
var shouldBeRendered = value;
var comment = $'epoxy-placeholder-comment');
//The element is detached but should be rendered. Replace the comment with the element.
if(isDetached && shouldBeRendered && comment) {
//The element is currently attached but should not be rendered.
else if(!isDetached && !shouldBeRendered) {
//If it's a first, we haven't created a placeholder comment node yet.
if(!comment) {
comment = document.createComment('epoxy-placeholder');
$'epoxy-placeholder-comment', comment);

This comment has been minimized.

Copy link
Owner Author

Prinzhorn commented May 2, 2014

Just found that it doesn't work on initial rendering since it happens before Epoxy adds the element to the DOM. I'll see what I can do. I was using it to hide elements in a list as the user searches, where this case naturally didn't occur.


This comment has been minimized.

Copy link

gmac commented Nov 30, 2014

When in doubt, make it async. Epoxy bindings allow you to define an init method (see, within which you should be able to define a setTimeout(..., 0) to schedule an initial rendering on the next event loop.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.