Pregunta

I'm using a dynamic template name. So I cant change out the template based on some selected values. What I'd like to do is fade out (or any animation for that mater) the old template elements before rendering the new one. There is this concept if you are iterating over a list but not for the root template itself. Has anyone tried this or got this to work?

¿Fue útil?

Solución

You could write your own binding handler:

ko.bindingHandlers.fadeTemplate = {
    init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        return ko.bindingHandlers['template']['init'](element, valueAccessor, allBindings);
    },
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        var value = valueAccessor();
        $(element).fadeOut(function() {
            ko.bindingHandlers['template']['update'](element, valueAccessor, allBindings, viewModel, bindingContext);
            $(this).fadeIn();
        });
    }
};

http://jsfiddle.net/xP7uy/

Otros consejos

I thought I share what I did when I faced the need for this and wanted a clean solution that didn't mixup too much with my views or viewmodels. I came across a css framework called Just Add Water CSS.

Animations don't work on older browsers but I guess fancy UI's don't anyway. But the premise of the framework is that many useful css3 animation class are defined and you just add them as you need them.

You can animate templates like this very easily:

<button data-bind="click: toggleTemplate">Toggle template</button>

<ul id="container" data-bind="template: { name: templateToUse, foreach: items }">

</ul>

<script type="text/html" id="myTemplate1">
    <li data-bind="text: $data" class="animated fadeInLeft"></li>
</script>
<script type="text/html" id="myTemplate2">
    <li class="animated fadeInLeft" >Value is: <span data-bind="text: $data"></span></li>
</script> 

And Vm to simulate template changes:

function vm(){
    var self = this;
    self.items = ko.observableArray([1,2,3,4,5,6]);
    self.templateSwitch = ko.observable(false);
    self.toggleTemplate = function(){
        self.templateSwitch(!self.templateSwitch());
    }
    self.templateToUse = function(){
        return self.templateSwitch() ? "myTemplate2" : "myTemplate1";
    }
}

ko.applyBindings(new vm());

Here is also a fiddle

There is a really good example here.

What you need to do basically is to add the animation code before rendering the template, you will see how in the example they create a custom bidding to call the animation code, I think you should do something similar, if you put an example of your code I might be able to help you more.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top