Using Isotope with Knockout.js

Knockout.js is a JavaScript library for writing MVVM style HTML applications. Isotope is a super cool jQuery plugin for fluid list animation – go play around with it here, it’s really impressive.

A question from a colleague prompted me to look at the Knockout.js documentation for the first time in a while and I noticed that there’s now a ‘afterAdd’ option available for the foreach binding. This allows us to hook in some code for manipulating an element once it’s been added to the list, intended for animation. I wondered if it was possible to insert Isotope into this process and it turns out it’s really easy – take a look at it working together here.

The code to do it was also really simple and demonstrates quite how handy Knockout is. I’m sure there’s some debate to have about whether the function for manipulating the element in the view really belongs on the ViewModel, but I’ll leave that for another day.

var $wordList = $('#word-list'),
    wordsViewModel = {
        words: ko.observableArray([]),
        newWord: ko.observable(''),
        add: function() {
            this.words.push( this.newWord() );
            this.newWord('');
        },
        wordAdded: function(el) {
            $wordList.isotope( 'appended', $(el) );
        }
    };

ko.applyBindings(wordsViewModel);

$wordList.isotope({
    layoutMode: 'fitRows',
    itemSelector: '.word'
});
<form data-bind="submit: add">
    <input placeholder="New Word" data-bind="value: newWord" autofocus />
</form>
<ul id="word-list" data-bind="template: { name: 'word-item-tmpl', foreach: words, afterAdd: wordAdded }">
</ul>
<script id="word-item-tmpl" type="text/x-jquery-tmpl">
    <li class="word">${ $data }</li>
</script>
Advertisements