Skip to content

Instantly share code, notes, and snippets.

@Prinzhorn
Last active November 5, 2016 08:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Prinzhorn/8080ec50934fbcb369f7 to your computer and use it in GitHub Desktop.
Save Prinzhorn/8080ec50934fbcb369f7 to your computer and use it in GitHub Desktop.
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.

Usage

<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 = $element.data('epoxy-placeholder-comment');
//The element is detached but should be rendered. Replace the comment with the element.
if(isDetached && shouldBeRendered && comment) {
$(comment).replaceWith($element);
}
//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');
$element.data('epoxy-placeholder-comment', comment);
}
$element.after(comment).detach();
}
});
@Prinzhorn
Copy link
Author

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.

@gmac
Copy link

gmac commented Nov 30, 2014

When in doubt, make it async. Epoxy bindings allow you to define an init method (see https://github.com/gmac/backbone.epoxy/blob/master/backbone.epoxy.js#L613-L618), 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