Remove element after applying bindings with knockout.js

There are some situations that you want to display something before the bindings get applied. For example, you might want to display a loading message until the bindings have been applied to this set of elements. Here is how you can do it.

<div id="container">
  <div data-bind="if: false">  <-- here is the trick
    <span>Loading ..</span>
  </div>
  <div data-bind=" --- something to bind by calling ko.applyBindings() --- "></div>
</div>

How it works? Simple. Once the bindings are applied, the binding on the div that surrounds the loading text will be removed automatically! 🙂

Dynamic Pinterest button

There are sometimes that you want to update the url or the media url of the Pinterest button dynamically. On Pinterest’s developer website there is nothing about it (weird!). I found a blog that suggests to remove & re-evaluate the pinit.js script, an approach that works but is very inefficient. I then by accident found on Github pinit.js uncompressed code and went through it & found out that it’s possible to update a button! Here is how you do it:

Step 1

You add a data-pin-build attribute to the script element that loads pinit.js and you give it a name, which will be the name of the method that you’ll be using for dynamically building Pinterest buttons (named build_pinterest_button in this example).

<script
  type="text/javascript"
  src="//assets.pinterest.com/js/pinit.js"
  data-pin-build="build_pinterest_button">
</script>

Step 2

Generate the new pinterest button (modifying the existing one might not work out because pinit.js replaces the button with a different one with a background image loaded from Pinterest’s servers). Then call the method you provided above on a parent container of the button (not on the button itself)

var $newButton = $('<div>')... //generate the new button
var $container = $(...)        //a parent container of the new button
build_pinterest_button($container[0]);  //re-build pinterest buttons inside container

And that’s it! You’ll get an update Pinterest button the same way as it does at the first time you load the script 🙂

If you run into any issues feel free to ask me (through comments below).