Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend namespaces with EmberJS

I've been programming in Javascript for a while. Recently I made quite a huge jQuery project and applied the Module Pattern as described in this wonderful article: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

This all went fine and dandy and the code looks slick and manageable, but I felt it could be better. I've spend the day looking for some Javascript frameworks, mostly ones that:

  • Have UI binding support
  • Have a templating system
  • Can work with jQuery
  • Help me organize my code in a similar way as I did with the module pattern

I've stumbled across frameworks like AngularJS, KnockOutJS, SpineJS, JavascriptMVC, etc. The one that really sticked out - and was quite praised - was EmberJS.

I decided to give it a shot, but it has not been easy. The availability of tutorials for EmberJS is very limited. After trying for a long time I managed to get some stuff running and I like what EmberJS does! There is only one thing I can't seem to figure out - which is also my question: How can I extend an Ember namespace (made with Ember.Application.create)?

For clarification: The old version of my project had a Core-namespace and a Util-namespace. Both contained their respective functions which all other classes could use. How can I have a Core- and Util-namespace with functions on top of the initial-namespace?

Do I just do:

MyNamespace = Ember.Application.create();
MyNamespace.Core = Ember.Application.create();
MyNamespace.Util = Ember.Application.create();

Or something else?

like image 464
Lennard Fonteijn Avatar asked Apr 22 '12 19:04

Lennard Fonteijn


1 Answers

You can't nest Ember.Namespace's (where Ember.Application being a subclass of Ember.Namespace), see issue #683.

Tome Dale, one of the core contributors, added an interesting answer about the layout of complex applications, see the comment.

So you can either just use App = Ember.Application.create() and create your controllers, views, etc under this namespace. Or you can - if you intend to reuse some code in other projects/applications - split the namespace's like this:

Util = Ember.Namespace.create({
    importantNames: 'Einstein'.w()
});

Core = Ember.Namespace.create({
    sqrt: function(x) { return Math.sqrt(x); }
});

App = Ember.Application.create();

...

App.myListController = Ember.Object.create({
    importantNamesBinding: 'Core.importantNames',
    sqrtBinding: 'Util.sqrt'
});

An Ember.Application extends Ember.Namespace, and adds functionality about handling events (click, ...). This stuff is useful when you write an application with views - in your Core and Util namespace you wouldn't need that stuff, that's why this is just an Ember.Namespace.

like image 85
pangratz Avatar answered Oct 13 '22 22:10

pangratz