Jeff
Jeff

Reputation: 12173

Using Knockout JS in an all-eyecandy scenario?

I am looking into KnockoutJS, and it looks really awesome, but I am not too fond of the way animations have to be implemented.

So, my question is, in a very animation-intensive application, should I use knockout? Is there a preferred, organized way of handling animations?

The way I see it, it's either DOM-hell or a slight mix of both. I read this article, and a few pieces of code, mainly the next one, already looks like a slight mess to me:

<ol data-bind="foreach: queuedPhotos">
    <li data-bind="attr: { 'data-id' : queuedPhotoId }, click: select, css: { selected: $root.selectedPhoto() !== undefined && $root.selectedPhoto().queuedPhotoId() === queuedPhotoId() }">
        <img src="img/cross.png" alt="Remove" title="Remove" class="remove" data-bind="click: remove" />
        <img data-bind="attr: { 'src' : smallImageUrl, 'alt' : title, title: title }" />
    </li>
</ol>

Upvotes: 1

Views: 126

Answers (2)

Anders
Anders

Reputation: 17554

Use computed observables, you should only use the data-bind attribute for metadata, like

data-bind="enable: canSave"

not

data-bind="enable: errors().length == 0"

There are also libraries that remove or minimize the use of data-bind attributes, I have made one that uses Convention over configuration check it out here

https://github.com/AndersMalmgren/Knockout.BindingConventions

With my lib this line of code

<button data-bind="click: save, enable: canSave"></button>

Would be

<button data-name="save"></button>

http://jsfiddle.net/3Ajnj/

Upvotes: 0

Sujesh Arukil
Sujesh Arukil

Reputation: 2469

Knockout is an excellent library for binding data and manipulating the dom. As far as the binding syntax hell that you mention, will eventually creep up if you have a lot of functionality handed to an element. Even simple things like a visible binding could see use of over 4 or 5 values to show or hide. This said, the typical approach is to create a custom binding handler to clean up that or use unobtrusive binding, something which Ryan Niemeyer talks about in his blog http://www.knockmeout.net/2011/08/simplifying-and-cleaning-up-views-in.html

There are various techniques (and knockmeout.net is an excellent resource, check out some of the videos from his presentation about unobtrusive bindings).

All in all, animations is not something Knockout does inherently. It leaves the implementation to the developer. Whether use jQuery to do it, d3.js or Raphael to manage canvas animations or the thousands thats already out there is totally up to you.

Keep your viewmodels simple (complex logic is not what I mean, simple means, it has a specific function and is not doing a zillion things in 1), keep your views simple and move the heavy lifting to a custom Binding handler or some other library.

Hope that helps.

Upvotes: 3

Related Questions