Rule Definition
When listening to events with $on, we should always remember to remove that listener with $off on destroyed(). This prevents us from having memory leaks.
Remediation
Clear the event listener
Violation Code Sample
const component = {
methods:{
listener(){
//do something on event
}
},
created(){
EventBus.$on('content-type-saving', this.listener)
}
_______________________________________
_______________________________________
<script>
export default {
methods: {
update() {}
},
mounted() {
window.addEventListener('hashchange', this.update, false); // Violation
}
}
</script>
Fixed Code Sample
const component = {
methods:{
listener(){
//do something on event
}
},
created(){
EventBus.$on('content-type-saving', this.listener)
},
beforeDestroy(){
EventBus.$off('content-type-saving', this.listener)
}
}
______________________________________
______________________________________
<script>
export default {
methods: {
update() {}
},
mounted() {
window.addEventListener('hashchange', this.update, false);
},
beforeDestroy() {
window.removeEventListener('hashchange', this.update, false);
}
}
</script>
Reference
https://cwe.mitre.org/data/definitions/404.html
https://auth0.com/blog/four-types-of-leaks-in-your-javascript-code-and-how-to-get-rid-of-them/#The-Three-Types-of-Common-JavaScript-Leaks
Related Technologies
Technical Criterion
CWE-1091 - Use of Object without Invoking Destructor Method
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.