I’m trying to write my first mixin for use across different backbone projects, and I’m just wondering how to namespace them.
In short, window. seems intrusive, I can’t namespace them under the project because the project name changes, and I can’t offer no namespace, because they only work if inside the same file.
So, in short, how should I organise/namespace my mixins so that they’re callable throughout a project?
Cheers…
The standard way would be to define a clean AMD-compliant module and then load it in your Backbone projects using a tool like Require.js. This approach doesn’t pollute the global namespace. If you don’t want to go all AMD, you can use the module pattern as explained in Douglas Crockford’s book “Javascript, The Good Parts”. It uses a self-invoked function to define your module, and returns the exposed object (or function). It does require a global namespace, though. A nice documentation of the pattern is here. In its simplest form it looks like this: