Reputation: 1
I am currently using the Durandal framework to build a simple site (my first with Durandal) and have a question on how to go about adding a simple javascript function. I want to call the function after the DOM loads, but am not sure how to attach it to the current viewmodel. The problem I am having is the function is being called before the DOM loads and the div ID hasn't been created yet, which in this case is "sb-search".
I then tried adding the function to the viewmodel:
define(["plugins/router"], function (router) {
var vm = {
viewAttached: viewAttached
};
return {
router: router
};
function attached() {
new UISearch(document.getElementById('sb-search'));
}
return vm;
});
but, to no avail.
Any help would be greatly appreciated. Even a simple tutorial on how to "document.write('Hello World')" would be helpful. Thanks!
Upvotes: 0
Views: 295
Reputation: 7261
This is not strictly related, but I'd like to add something to what was said in the comments: you most likely shouldn't scan the global document in the attached
handler. When it's called, composed views may not be, well, composed/attached themselves yet, and in general it's a good idea not to make assumptions about the global state. Also, you can gain performance by not scanning the whole DOM.
When calling attached
, Durandal passes the root DOM element of the view bound to the view model as the first argument to the function. Use it to restrict search. If it's in a child/composed view, use the compositionComplete
handler, called after all composition in complete (the event "bubbles up"). If it's in a parent view, use the second argument passed to these functions. If it really sounds too complicated, consider that your design might be flawed itself, look for MVVM guidance.
For completeness:
The comments mention that
attached
!= viewAttached
),attached
handler called by Durandal, know that viewAttached
is deprecated in favor of attached
.router
property before you return your vm
(view model for sure), although that might be a left-over from some tests you did and copy-pasted here by mistake.Upvotes: 1