I was working on a Backbone application that updated the DOM when a response was received from the server. In a Backbone View, the initialize method would perform some operations and then call the render method to update the view. This worked fine, however there was scenario where in I wanted to perform some tasks before and after rendering the view. This can be considered as firing an event before and after the function had completed its execution. I found a very simple way to do this with Underscore's wrap method.
Underscore comes with several utility functions and one of them is the wrap method. According to the documentation of the _.wrap method:
This was exactly what I needed. Here's is the code that used the _.wrap method to wrap the render function: In this gist, you can see that the render function is wrapped using Underscore's wrap method and inside the wrapper, methods - beforeRender and afterRender are being called. On calling the render method the wrapper function is executed:
The output shows that the log messages defined in the beforeRender and afterRender methods gets executed.
Underscore comes with several utility functions and one of them is the wrap method. According to the documentation of the _.wrap method:
"Wraps the first
function inside of the wrapper function, passing it as the first argument. This allows the wrapper to execute code before and after the function runs, adjust the arguments, and execute it conditionally."
This was exactly what I needed. Here's is the code that used the _.wrap method to wrap the render function: In this gist, you can see that the render function is wrapped using Underscore's wrap method and inside the wrapper, methods - beforeRender and afterRender are being called. On calling the render method the wrapper function is executed:
Before render
Inside render
After render
The output shows that the log messages defined in the beforeRender and afterRender methods gets executed.
Comments
Post a Comment