Tuesday, 14 April 2015

RequireJS + AngularJS + A different spin

I keep on meaning to post this tutorial here -- it's been on github for a while and I somehow didn't manage to add it here...
Anyways, this was part of a discovery mission for using RequireJS and Angular to build a simple app. Angular because I like it as an MVC framework for Javascript and RequireJS because, really, who wants to maintain script tag spam in your SPA? Not me, not after I had a page with 20 inclusions and realised it was indicative of something horribly wrong.
The method I chose also makes this code easier (for me) to test: Angular has some great mocking and testing functionality, but in the face of Karma+Jasmine, it just seems like far too much effort to figure out another mocking framework -- not to mention that I find the concept of having to $apply to get Angular to run its magic a little counter-intuitive and a little out-of-place in a test (imo).
So I flipped this a little on it's head: the controller module in this project doesn't actually register a controller -- it returns the configuration which can be used to register a controller -- which is consumed by app.js so that routing can work with the configured controller. This frees me up to test the controller in a simpler way: test that the array has the correct dependencies, in the correct order (typically, just '$scope') and then test that the scope passed in is modified in the expected way (properties and methods added and the methods work as expected). I must point out the obvious here: that I'm not inclined to use Angular factories and services -- but who needs them if you have RequireJS and go the prototypical route?
But enough blah-blah. If nothing else, this tutorial can demonstrate one way to do it. I've also made JQuery private so that the only library in the global scope is Angular -- and this was mainly so that angular-route would load up correctly. There's probably a better way do to this too (I've read about AngularAMD and some others; just haven't play-tested them), but I was satisfied enough with the final result -- and it might prove at least a little interesting for some (:

No comments:

Post a Comment

What's new in PeanutButter?

Retrieving the post... Please hold. If the post doesn't load properly, you can check it out here: https://github.com/fluffynuts/blog/...