As much as I love working with Aurelia, the documentation can be confusing for newcomers to the framework (forgivable considering it is so new and evolving). The purpose of this post is to quickly touch upon ViewModel methods that get called at various parts of the ViewModel activation process.
The two methods I have found myself using the most are attached
and detached
as sadly a project I am working on still uses jQuery libraries like Select2 for creating custom styled dropdowns.
Once you become familiar with these events, you can understand the right place and time during Aurelia’s execution context when you should perform a particular task or execute a plugin on the DOM.
attached()
This method gets called when the View is attached to the DOM. Here is where you will do your DOM manipulation, wrap elements in jQuery objects or whatever you like. All work with the DOM (especially plugins) should be done within this method.
detached()
This method is called when the View is detached from the DOM. If you registered events in the attached
method, you would probably unbind them in here. This is your chance to free up some memory and clean the slate.
bind()
This method happens after binding occurs, but before the DOM attachment. This is where the DataBinding engine binds the contents of the View.
unbind()
This method is called when the DataBinding engine is unbound from the View.
Conclusion
Knowing about the above methods on your ViewModel’s will save you a tonne of headaches down the track. If you have any questions as to which method is the right one to use or more in-depth information, just leave a comment for a timely response.
Great job on this blog. We’re using Aurelia and your blog is one of the top resources I’ve found.
Regarding this post, what are some use cases you’ve ran into where you needed to leverage unbind?
Cheers Forest.
In the instance of unbind, the only use-case I think it serves is for cleaning things up. If you’re extending how the binding is being handled, in the unbind method you would clean up any custom binding behavior you have created.
This is very helpful! Thanks for sharing!
Hi Dwayne, I think it would be worth differentiating between views and components (views being the class/object instantiated within a , components being custom-elements usually), and bring activate/deactivate into the mix with the lifecycles, and where they fit with respect to each other. Wouldn’t hurt mentioning also and how compose will then attempt activate/deactivate on a view/component.
I also prefer to see your lifecycle methods listed in their actual lifecycle order and numbered.