I was wondering how to create a namespaced object using SproutCore’s OOP implementation. I’ve worked with Joose in the past and namespaces are automatically generated, for example:
Class('MyNamespace.AnotherNamespace.ClassName',{})
But in SproutCore, it looks like you may have to create the individual objects yourself? I feel like that’s a bit tedious. Am I missing something?
Any help would be greatly appreciated.
Thanks
SproutCore classes are just as easy to create: SC.Object.extend({…}). And any unreserved property of any object can be treated as a namespace. Just drop in an SC.Object (SC.Object.create). Per hvg’s answer, you can declare it when the Application is instantiated, or later in another file:
This isn’t much more code than your Joosie example. Your observation that the namespace isn’t automatically created for you is correct, but that has semantic benefits: you can define all of the namespace’s contents at the same time that you create it, which encourages the centralization of code; and it prevents the bug where you accidentally autodefine a typoed namespace.
The key insight here is that your application object is not just a namespace, it’s an active, dynamic instance of a class that provides application-y functionality. The fact that all of your application’s code ought go in the application object creates a sort of natural namespace, and I find that most of the time my sub-namespaces work the same way (myApp.mainPage, myApp.contentController, myApp.remoteDataSource, myApp.statechart). You are certainly welcome to organize your code into dedicated namespaces via a dedicated instance of SC.Object, and I often do, but SC applications tend to self-organize to a high degree.