简体   繁体   中英

Durandal - Can I have one function that always gets called after binding is complete?

I'm working on a SPA built with Durandal and Bootstrap. We recently started trying to add TabDrop to deal with smaller screens. Tapdrop automatically shoves any items that don't fit on the first row into a drop down.

I got our app to work by adding $('.nav-tabs').tabdrop(); to the attached function in any viewmodel that has tabs. This works, but it's clunky. (Only attached() works, activate() is too early and then the tabdrop does not work.)

So, that makes me wonder: Is there a way I could plug in this function to always get called directly before or after attached()?

What comes after attached is compositionComplete . You could move your DOM accessor there.

But $('.nav-tabs').tabdrop() is not a Durandal-based approach. Assuming that the compositionComplete handler works, it would look like this:

compositionComplete = function (view, parent) {
    $(view).find('.nav-tabs').tabdrop();
}

This approach constrains the search over the DOM to the view participating in the composition. You can constrain in the same way with the attached handler, as the view is exposed there as well.

An even more elegant approach would be to write a custom Knockout binding.

The reason activate is too early is that the DOM isn't fully constructed at that point.

Yes. There are a number of callbacks that can be fired during the activator lifecycle:

activate() Composition & Activator Allows the new object to execute custom activation logic.

binding() Composition Notifies the new object immediately before databinding occurs.

bindingComplete() Composition Notifies the new object immediately after databinding occurs.

attached() Composition Notifies the new object when its view is attached to its parent DOM node.

compositionComplete() Composition Notifies the new object when the composition it participates in is complete.

For more information, please see the docs here: http://durandaljs.com/documentation/Hooking-Lifecycle-Callbacks.html#combined-lifecycle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM