mehrandvd
mehrandvd

Reputation: 9116

Animate on changing the value of an observable in Knockout

I want to add animation when working with observable not observableArray which is already available in knockout documents.

Consider a <div data-bind="text: fullname"/> which fullname is an observable. I want the content of <div> element animate and slides down when the value of fullname changes. Something like:

<div data-bind="text: fullname, transition: slideDown"/>

Also, I'm using Durandal if it helps.

Question: How can I assign transition animations to observables?

Upvotes: 2

Views: 716

Answers (2)

sroes
sroes

Reputation: 15053

You can create a custom binding handler which does the animation for you:

ko.bindingHandlers.textSlide = {
    init: function(element, valueAccessor) {
        $(element).text(ko.unwrap(valueAccessor()));
    },
    update: function(element, valueAccessor) {
        var value = ko.unwrap(valueAccessor());
        if (value != $(element).text()) {
            $(element).slideUp(function() {
                $(this).text(value).slideDown();
            });
        }
    }
};

See http://jsfiddle.net/ro0u9Lmb/

Upvotes: 0

Robert Slaney
Robert Slaney

Reputation: 3722

The beforeRemove and afterAdd are just wrappers around the subscribe function.

ko.bindingHandlers['transition'] = {
  init: function(element, valueAccessor, allBindings) {
    var transition = valueAccessor(),
        target = allBindings.get('text'),
        subscriptions = [ 
          target.subscribe(target, onChange),
          target.subscribe(target, onBeforeChange, 'beforeChange')
        ];

    function onChange() {
      // handle transition when target updates
    }

    function onBeforeChange() {
      // handle transition BEFORE target updates
    }

    ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
      subscription[0].dispose();
      subscription[1].dispose();
    });
  }
};

Upvotes: 2

Related Questions