Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.datepicker call inside of Durandal activate function not working

I'm Composing this in a view, then trying to call .datepicker() on the result, but nothing happens.

The compose container

<div>
<!--ko compose: { model:'viewmodels/schedule', view: 'views/schedule.html', activate:true} -->
<!--/ko-->
</div>

schedule.html

<div class="schedule-editor">

</div>

And the schedule module

define([], function () {
    var vm = {
        activate: activate,
    };
    return vm;

    function activate() {
        $('.schedule-editor').datepicker();
        console.log("activated schedule module");
        return true;
    }
});

Console logs "activated schedule module", but the datepicker is not created. If I go to the chrome console and run the jQuery call, $('.schedule-editor').datepicker(); it brings up the datepicker just fine.

The Durandal docs claim that the activate function is called after the DOM is full composed, so I don't know what else to try.

like image 333
Kal_Torak Avatar asked Mar 22 '13 21:03

Kal_Torak


Video Answer


2 Answers

Like nemesv mentioned you should use viewAttached instead.

define([], function () {
    var vm = {
        viewAttached: viewAttached,
    };
    return vm;

    function viewAttached(view) {
        $(view).find('.schedule-editor').datepicker();
        console.log("activated schedule module");
        return true;
    }
});

Activate happens in the lifecycle before your model has been data-bound to the new view and before the view has been added to the dom. viewAttached happens after the view has been data-bound to your model and attached to the dom.

EDIT

Durandal 2.0 has renamed viewAttached to attached

like image 150
Evan Larsen Avatar answered Sep 30 '22 15:09

Evan Larsen


There is another approach to this that stays true to the declarative UI philosophy that knockout.js and durandal are striving for.

It will allow you to declare the datepicker within the HTML like this:

<div class="schedule-editor" data-bind="
    jqueryui: { 
        widget: 'datepicker', 
        options: { 
            // you can set options here as per the jquery ui datepicker docs
        } 
    }">

</div>

Simply include the jquery ui widget bindings found in this gist: https://github.com/SteveSanderson/knockout/wiki/Bindings---jqueryui-widgets

Make sure you include the above javascript after you have loaded jquery, jquery ui and knockout.

like image 32
Alexander Preston Avatar answered Sep 30 '22 15:09

Alexander Preston