Tag Archives: Angular

[repost ]Angular项目构建中的组织结构

original:http://developer.51cto.com/art/201409/452809.htm

如果说还有一个很重要的原因去让我们孜孜不倦的完善架构,就是为了不在项目日益庞大的时候无法有效的维护,个人感觉这是最主要的一点,就是通过清晰的代码和结构,降低维护的成本。

AD:2014WOT全球软件技术峰会北京站 课程视频发布

前几天刚刚把项目的组织结构进行了一次重构,这是前端项目至今第二次进行组织结构上大的变化,也是一个”folder by type”到”folder by feature”的过程.

为什么有这个过程?

因为感觉到项目的日益庞大,每次修改一个地方我可能要打开三四个文件,比如说一个页面上的哪里要修改.那么首先是页面的HTML,然后是Controller,Less,对应接口的service文件等等.整个项目是我一手构建的可能还不会出问题,只是找的时候要回想一下对应的文件,但是如果一个新的成员加入进来,不免就有些疏漏,因为他也很难确定一个页面上的局部变动,到底要涉及到哪些文件.

最开始在项目刚刚构建的时候,也就是只有一个页面的,就开始按照文件类型进行项目的组织.不过随着项目的庞大,以及各方面其他的影响,逐渐,按照type进行划分已经出现了职责不清晰的感觉.

最开始项目的结构大概是这样,太具体的有点记不清了,大概是这样的:

  1. — static
  2.   — js
  3.     — app.js
  4.     — routers.js
  5.     — services.js
  6.     — directive.js
  7.     — filter.js
  8.     — controllers
  9.       — userController.js
  10.       — someModule.js
  11.   — less
  12.     — index.less
  13.     — user.less
  14.     — someModule.less
  15.   — build
  16.     — all.2014090901.js
  17.     — all.2014090901.css
  18. — templtes
  19.   — index.html
  20.   — user.html

基本结构就是按照功能对Controller进行划分了,因为做的Angular SPA所以基本上一个Controller对应一个子页面,然后将所有的js以及less合并压缩出来,在index页面加载.当然其实还做了一些更细致的工作,这里只是说一下项目的雏形.

接下来都做了哪些改变?

与其说接下来做了哪些改变,不如说一下有哪些东西促进了我们要进行改变.说到这在岔开一个话题,什么叫做稳定良好的文件组织结构,一个我现在下的定义就是”健壮并包容”.当一个东西发生变化的时候,你当前的组织结构能够以很小的代价去适应新的变化,而不是整个项目大改特改,甚至牵连到代码.

当雏形完成后,项目日益增大,有两个task进入了要考虑的流程.一个是关于项目的自动化构建,包括是库文件的管理,库之间的依赖关系,代码的压缩合并等,还有静态资源的版本号,开发模式和发布模式下不同代码构建等等.另一个问题就是URL的设计,怎么和文件的组织结构保持高度统一.

这两个问题都比较杂,先说URL的设计吧.

关于”好的URL设计”的定义有好几条,可以自行百度,我不打算抄袭百度百科了.只谈我认为最重要的就是对用户的友好,什么叫URL对用户的友好呢?说白了就是让你的URL一看就懂,一猜一个准.我认为这样设计就可以了,可能你会说了谁会无聊到去记住URL地址呢,想要以后访问收藏一下就可以了.

这个我没什么兴趣去反驳,不过你怎么看不见百度或者淘宝的网站将地址设计为”www.baidu.com/hsakudhkajshdgjasgdjhsgfjhsagfjhsdgfjhasgfj786347823yuisbhdufy”.

URL的语义化很大程度上表达了对用户的友好.比如我现在”/restaurant”,”/restaurant/new”,”/restaurant/2″,”/restaurant/2/edit”这几个URL对应的页面分别是:

餐厅页面(列表数据),新建餐厅页面,餐厅id为2的餐厅页面,餐厅id为2的餐厅编辑页面.

很容易猜到不是吗,将2改为其他对应的id也能访问到指定的餐厅页面.这个URL映射关系从结构上说就应该与我们的文件夹结构对应,也就是应该有一个restaurant文件夹,然后里面有详情,新建,编辑等页面以及对应的其他文件.所以基于良好的URL设计,我们是需要一个符合语义的组织文件结构的.

项目的自动化构建怎么牵扯到文件结构?

每个小话题感觉都能引出一些详细的深入的东西,项目自动化构建为了解决什么问题?这个解决了很多问题,但是对于一个Angular SPA来讲主要有两个需求.一个是将静态资源合的整合,比如合并压缩,发布时使用带有版本号的静态资源.另一个是开发过程中的一些Less文件以及JS文件的重新编译,页面自动刷新等.

简单说一是为了发布,一是为了开发,为这两个步骤更加便捷有序做出一些努力.

在上面的过程中,不管是开发还是发布,都会生成很多build出来的文件,这也会影响到你对项目目录和文件组织的调整.

新构建好的项目结构

每一次对于项目的修改都涉及到方方面面的东西,很繁杂,随着项目的日益庞大,这种修改的成本也会越来越高,所以及早确定一个好的架构是很迫切的.先给出当期啊的结构:

大致说一下现在怎么划分的,因为是SPA所以肯定有一个index.html作为页面的承载,app.js是angular的main文件,app.less是所有Less文件的入口.

components是angular的各个组件,包括common,services,directives,filters,router,run.js(这个主要是放置一些需要随App一起启动运行的代码,例如插件初始化配置,以及类似路由监听处理事件等).

一个子页面按照功能模块划分在modules中,对应的Controller的JS文件,Less的CSS文件都在一个文件夹内.

build目中的内容全部是生成的,我使用了Bower和Gulp搭配使用,自动化构建项目.

这样目录结构就清晰了,公共的部分被单独划在一起,每个页面对应的相关文件被组织在一起,然后按照功能安排进行划分.这样在维护的时候就能很容易找到要修改的相关文件.同事日常开发和项目发布都是用build中的文件,里面有两套不同的文件对应开发和发布。

这样感觉整个项目都清爽多了.

项目构建之路岂止于此

因为篇幅所限很多东西还是没法一起交代清楚,比如Controller的职责划分,services的结构,以及Bower和Gulp如何配合进行完整的项目构建.这些过后可能会在Github上留一套架子,有兴趣的可以留言。

虽然感觉很多东西没说明白,不过关于组织结构的事儿,大概也就是这些了.只是项目的构建之路漫漫而修远,最后还有点心得和大家分享一下。

项目的构建做到现在只能说完成了初级的一步,如果稍微好点说,算是中级吧.那么理所应当该有个高级或者说终极目标.angular是一套框架而不是库,这就给了我们很多发挥的空间,从现在的情况来看,还有那些不足需要改进的东西,我总结了一些点,当然这些点对大多数项目可用:

 

各部分之间的耦合度,是否做到深度解耦。

Controller的职责是不是过大,不单单是业务,很多乱七八糟的东西都丢到Controller中,导致形成了’super controller’。

一些公共的东西是不是没有抽取出来,还在重复copy代码。

MVVC的概念,是不是发觉自己在angular中没有M的概念。

用面向对象的思想看看架构和代码,有没有做到职责单一,开放闭合.

其实还有很多东西需要改进,我也一直在慢慢组织.可以说,一套搭的比较完善的架子有两个最为突出的特性.其一就是结构清晰维护方便,因为每个部分职责单一,对修改闭合,对扩这开发.另一个特性就是开发效率极高,大量的内容被抽象出来,做成公共的组件,70%的代码已经被写完了,只要写业务那部分即可。

如果说还有一个很重要的原因去让我们孜孜不倦的完善架构,就是为了不在项目日益庞大的时候无法有效的维护,个人感觉这是最主要的一点,就是通过清晰的代码和结构,降低维护的成本。

原文出自:http://my.oschina.net/blogshi/blog/322883

【编辑推荐】

[repost ]Backbone or Angular or Ember? Here is my choice and why

original:http://www.100percentjs.com/backbone-or-angular-or-ember-here-is-my-choice-and-why/

mvclogos

I’ve spent the last year neck deep in the main MVC / MV* whatever frameworks for Javascript. It  was a very hard choice to pick a favorite and stick with it. I started out with Backbone, moved on to Angular and finally settled on Ember. This convoluted process is the reason I haven’t blogged in a few months, I really had to pick what client-side framework to blog about. This is my reasoning:

Backbone is great,  minimal and not opinionated which I like, as such it resembles classic Javascript the most and has the least steep learning curve, but the main point against it – that you need a lot of boiler plate code to make it work well – is valid. This means that you have to do the architecture and wiring yourself and can cause a giant mess which is not much better than spaghetti code jQuery really, or to avoid that you either have to reinvent the wheel  to set up your project or bring boilerplates into your projects every time. You also have the option of bringing in extensions like Marionette and Layout manager, but at that point it’s not so minimal and becomes opinionated which kind of beats the purpose of using Backbone in the first place. Besides that, Backbone is starting to feel old and lacking features compared to the newer frameworks. I also dislike the way Backbone doesn’t have actual controllers, it has views and templates, there is no clear separation between the business logic which in my mind belongs in a controller, and UI interactions which do not. This makes it easy to end up with an app which doesn’t allow easy iteration through UI variants.

Angular is really impressive at first glance, it can do quite a lot of amazing stuff, like 2-way bindings, helpful out of the box directives and filters. Angular also has quite nice support for module dependencies and injections, it has services and factories which become reusable parts for your app. It also enforces quite strongly separation between logic and presentation which allows you to make UI presentation variants quickly while the underlying logic remains the same. In my opinion Angular is the closest thing to a real software engineering solution for front-end web development, in some ways it resembles Java, in some ways .NET.  That all sounds great, why did I not stick with it? It is mostly personal preference, but I dislike how extremely opinionated Angular is and how much it deviates from classic Javascript UI development. Unless you do everything according to the “Angular way” you end up confused and fighting the framework instead of gaining benefit from using it. Directives which are super complicated and odd are a true embodiment of this, but in Angular almost everything is done differently. This means that  prior experience in creating UI with Javascript is rendered almost useless. No matter who you are, you have a very steep learning curve and along the way you really start questioning the benefit. At times I do feel enabled by Angular’s different paradigm, but far too often I find myself frustrated. The framework is loaded with syntaxes, concepts, keywords, patterns that exist nowhere, but in the Angular framework and memorizing and gaining this skill doesn’t make you a better overall software engineer or Javascript coder, it makes you better in Angular. It reminds me a lot of the .NET framework in that way which I ultimately also decided is not worth it.

Ironically I’m by far least experienced in Ember, but I like it the most already (I’m hoping that doesn’t change and I end up having to learn yet another MVC framework). Ember can do almost all that Angular can and equally fast or faster, and it manages to achieve that without deviating so much from classic Javascript syntaxes and patterns. It looks quite a lot like Backbone, but where Backbone is either loose or lacking features, Ember has it covered and enforces best practice. It is closely tied to the Handlebars templating engine which I believe is the most superior and is also used by 2 other Javascript tools which I love using –Ghost and Assemble. This means that whether making static sites, CMS, blog or single page application with MVC,  or combining all of those, you can re-use your templates and helpers from Handlebars, you can also bring in anyone’s pre-made directives and helpers and gain  a very big toolset. Unlike in Angular, in Ember you can use any of jQuery’s powerful features which we all know and love (we Javascript devs that is). You can transfer almost all your prior skill and knowledge to Ember development. Ember  feels to me like Backbone on steroids – it has a similar feel, but is a lot more powerful and structured. I also like that it has standardized its templating and patterns, this way unlike with Backbone, you can borrow from any pre-existing Ember app or example.

For these reasons I chose Ember.js and am excited to be able to focus and devote my further writing in this blog to it.

[repost ]Why AngularJS is generally better in Angular vs Ember vs backbone

original:http://voidcanvas.com/why-angularjs-is-generally-better-than-emberjs-and-backbonejs/

“Angular vs. Ember vs. Backbone” generally turns into a war in most of the discussion forums. But in my personal opinion, the emphasis should be on “what kind of application you are developing” that brings us to the question “Angular, Ember or Backbone, which one is better?” Because all of them have their own advantages and disadvantages. But I personally have found Angular more preferable in most of the cases.

Comparing the Features

Backbone Ember Angular
Framework MV + VC Pure MVC MVW (Model View Whatever)
Template Support Uses underscore.js( an embedded template engine which allows logic inside template code) Uses Handlebars(a logic less template which doesn’t allow JS code to be written inside it but has provided some features to implement some logic) YES. It doesn’t require any other separate template engine.(Also doesn’t support any 3rdparty template engine)
Nested Template Support No Ember + Handlebar has support, but only Handlebar doesn’t support Yes
Auto Binding No Yes. (Supports auto binding but when used template engine other than handlebars auto updating turns off.) Yes
Routing Yes Yes Yes
Dependency Has a dependency for underscore.js Handlebar.js for templates, and jquery 1.7 or higher No Dependency
Compatible with other frameworks Yes Yes Yes
Additional Features 1. Computed properties and its binding
2. Data formatters
DI, mocking, directives, watch expressions and its binding, HTML5 validations

Templates

Backbone: In backbone, you can choose your own template engine, no matter whether it’s String or DOM based. Usually people prefer handlebars.js, a string-based template library.

Ember: It uses built-in string-based templates (mandatory). Arguments in favor of string-based templates include “it’s faster” (debatable) and “theoretically, the server can render them too” (also debatable, as that’s only true if you can actually run all of your model code on the server, and nobody generally does that in practice).

Angular: Angular uses built-in DOM-based templates (mandatory). DOM-based templates means doing control flow (each, if, etc.) purely via bindings in your actual markup and not relying on any external library. Argument include “it’s faster” (debatable) and “the code is easier to read and write

In Angular the DOM structure is created on pageload. Suppose you have multiple templates in your page and you don’t want to show them at a time. In that case also you have to define those at page load lavel, if you use angular, which will unnecessary create few extra DOM elements. But in Ember you can insert dynamic templates as it uses string based templating method. So in this perspective Ember and Backbone’s string-based templating may go handy, but if you talk about data binding, DOM-based templates provides you better performance. According to the Angular developers’ team, in near future DOM-based templating will be natively supported on browsers and when this happens, Angular apps will run way too faster, so we should best prepare ourselves for the future by adopting it now. AngularJS is from Google, so they are already working on this with Chromium and standards bodies.

Model Mutation:

Backbone & Ember: In model mutation both Backbone and Ember follows almost the same structure and flow. They use getters and setters to get or set a value and this is also an efficient way to learn the model change and accordingly reflect it to view. But while rendering the data elements, ember adds observers to each element. As the observers are heavy, so it makes the rendering process slower.

Angular:  Angular doesn’t use the traditional getters and setters like backbone and ember, rather it uses Dirty Checking to learn the model change, which is way too faster (according to the angular team).

Angular uses Dirty Checking, which is based on the lexical scoping in js and helps in garbage collection too. Not only that, angular lets all the model mutation to happen first and then inform all the listeners in a consistent state. This helps to prevent wrong data operations.

Performance:

Performance is something, which you just can’t judge only basing on the pros and cons of the framework. Rather, it completely depends on your needs and the type of app you are developing. The key performance judging factors are given in the examples below.

Eg 1: Suppose, in your app, you are using huge number of data. So if you use ember, you will find the app is taking too much time to get loaded; and that’s because ember adds observers to each element. So this thing makes the rendering very slow in comparison with backbone and angular. But once the app is loaded, and you expecting your view to reflect the model change immediately; well angular will make you sad. Because, as it don’t have an observer attached with each element, so to learn the data change, the angular controller has to traverse the whole data model (dirty checking). But if your app doesn’t depend on fast data binding; rather you want your app to load faster, angular is the best option.

Eg 2: Angular is sort of a HTML compiler. It has the power to manipulate the normal behaviour of your HTML. Suppose, you are printing the data of your model one by one using {{#each}} helper in ember (actually in handlebars), or using the ‘For’ loop of backbone. In this case ember will run a loop to print them; and as you know, loops are always heavy and time consuming operations. But in a similar situation, angular’s ‘ng-repeat’ will fetch the data as a whole and will put it directly on your html. This is a much faster process.

Eg 3: Suppose your app is a continious animation based app, where you have to perform some animation to each element in your model (let your model has the instances of few html elements or something similar to that). So here, ember’s observers will be of no use; cause no matter what, you have to change the model and view continuously. So angular’s continuous checking or dirty checking may play a role for you here.

So, this is how, performance is a variable thing, which varies from projects to projects, scenarios to scenarios, environments, dependencies and many more. So only that framework can give you best performance which is the most compatible one to your app.

Here is a Live Performance Testing with example.

Learning & Development

Backbone: Basic backbone is very easy to learn, but while developing, you will find it was not enough. Because only using backbone you can’t structure your code much. It needs more libraries and templates to make a proper project.

Ember: Ember has more structured documents and it’s also not that tough to learn. Its implementation (with handlebars) is much similar to the other process and object oriented programming.

Angular: Angular is a little tricky, because it’s somewhat an extension of HTML. But once you get this html processing, it will become the simplest framework to learn.

Angular is comparatively simple to learn, and more simple to develop. A friend of mine made a widget on backbone, which was of more than 3800 lines. It has come down to 725 lines when rewritten in Angular. And the code was more structured and clean. Simplicity is one of the best plus points of Angular.

Testability

Testing is possible on all the frameworks, if you learn the right pattern to develop your project. Your modularity and ability of dependency injection are the key parts to have a testable code. And modularity and dependency injection are two of the major features of angular. Angular itself was built keeping the testing facility in mind. So I think, in testability angular is ahead of Backbone and Ember.

Projects point of view:

While developing, or before starting the development of a project you need to keep in minds many points; and these really plays the role behind the selection of the framework.

There was a time when the codes of backbone seemed to be very clean and structured. But ember and angular showed the codes can be more cleaner and structured. Let’s watch these three frameworks as project developers point of view.

Backbone: Maximum people has worked with backbone; so it’s much easier to found an experienced backbone developer. There are lot of help available there in the net about backbone. It won’t cost you much to train your people. So in this point of view, backbone is good.

Ember: The best thing about ember is, if forces you to follow the ember way; and if you don’t, the app will never run. Though for beginners it will be a headache; but the best thing is; as everyone will follow the same way to develop the app, so it will be well structured and very very easy to maintain in future. Everyone is not a good coder; and humans always like shortcuts. So, if you are developing a huge project with lots of developers, they can’t code any logic wherever they want. They have to strictly follow the MVC structure and ember’s way of coding.

Angular: What if you don’t have much time to develop your project? Not much time to learn frameworks? Then you must go with the angular way. Angular also makes the code much more cleaner, structured and maintainable if the developer has knowledge of MVC development. It reduces the lines of codes like anything.

Conclusion

I think comparing backbone with Ember and Angular is unfair, because it’s more like a library than a framework. So it won’t provide as many features as provided by the frameworks like Ember and Angular.

It’s also not like a single framework will be always the best one. I’ve also given examples for that in this article. There are lot of factors you need to take care of before selecting the javascript framework for your application. I’m working in a travel service company right now and we selected Ember over Angular for our development, because it was more suitable to our previous architecture and widget based development. Similarly lot other environmental factors will come.

Every framework has its pros and cons. But what we need to consider is, the requirement list of our project and the adaptability of the framework on those requirements. But as an overall view, I’ve found out angular is very easy to learn (even a guy who didn’t work much with MVC and just knows simple HTML and javascript, can learn it very easily); it reduces the number of lines in your code more than backbone and ember; if your data model is not huge, it provides you fast rendering and execution; manipulates the DOM directly; makes your code testable and lot more. That is why I’m considering Angular a better option than Ember and Backbone generally.

[repost ]Frameworkless JavaScript

original:https://moot.it/blog/technology/frameworkless-javascript.html

Why Angular, Ember, or Backbone don’t work for us

Moot is a special discussion platform with ambitious goals. While the server side is fanatically optimized for performance, the client has its own goals: simple API, small size, and quick release cycle. The code is written from scratch and is split into more than 50 files. A client-side framework such as Angular or Ember were out of the question.

Here’s why.

API first

My primary goal for the Moot client was a simple API. It had to be easy to use, have no extra properties or methods, and shouldn’t present new programming idioms. It would feel familiar for a newcomer. Not only would the end users be using it, but I would personally be using it for years to come, since the whole web UI is built on top of it.

When starting to design an API I always want to start from scratch. Just a clean table, a pen, and paper. I’m thinking about the API and the end user only. No frameworks are present at this point.

This API becomes the Model in MVC, in a form of “Plain Old JavaScript Object” (POJO). For framework advocates the API is a “single source of truth”. The API runs on browser as well as on server (node.js). It’s a completely separate, testable unit.

I really don’t want to clutter the API with framework related methods and properties. BothBackbone.Model.extend and Em.Object.extend add tens of redundant methods, adding complexity for the end user. This is simply not acceptable from our minimalistic approach.

Small size

A smaller file is faster to load and saves us money in bandwidth costs. That’s an instant benefit. The biggest advantage, however, is in the code maintenance. A smaller codebase is easier to handle, faster to learn, and has less issues.

Currently the Moot client weighs 89kb when minified, 32kb when gzipped. This is roughly 10 times less than other discussion platforms out there. Size definitely matters. And when 50% of all internet usage happens from mobile devices (1), developers are seeking for the slimmest tools for the job.

The following table gives you an idea of the size had we used a separate tool for each feature. I’m listing projects that I would have used — not the biggest projects I could find just to look good in comparison. The sizes are from minified files.

Templating, data-binding, form validation Backbone.js 33.9kb
Syntax highlight with support for 20+ languages Rainbowjs 28kb
Tooltips, overlays, select boxes, tabs etc.. Misc. tools 20kb
WebSocket communication socket.io 40kb
Markdown parser markdown-js 23kb

That’s around 150kb of code before the actual development has even started.

Currently, the combined size of Moot with all the UI views and controllers (the glue between API and views) is just 40kb when minified. How much would that be with a framework? It should be much smaller if the purpose of a framework is to reduce the amount of work to achieve the goals.

40kb is easy to manage and build upon. I can add massive amounts of features before things start to get complex.

Full control

Moot uses native pushState for managing URLs, John Resig’s “micro templating” (6) for views, and internal communication between model and views happens with a custom event library. There is no router or automatic data-binding.

Everything works exactly how we want it to, and the bugs are easy to find. There is no wasteland of unknown code of which you have no idea how it works. There are no mysteries and the stack traces are shallow. We can structure the code according to the specific needs of the application – there is no framework to dictate how things must work.

No mixed programming styles.

No external package updates.

No dependency hells.

It’s fun to make a new release every week.

Special needs

The Moot client is a single JavaScript file including all the HTML code as well. The client renders itself inside a single anchor (A) tag when the page loads. The product packaging and bootstrapping are very different from a traditional single-page application.

Moot servers must be able to notify clients at any time. Both clients and servers communicate in a peer-to-peer bi-directional fashion.

We send JSON-RPC messages with WebSockets. REST is not an option here: real-time applications such as Moot cannot be built on it, because it uses a request-response pattern and does not understand things like push events.

Today’s frameworks, such as ember data, are REST-oriented and the examples and documentation are based on REST. WebSocket examples are missing or experimental.

Moot’s engineering challenges were unique.

Technology lock-in

If you look at the history of frameworks in any programming language, it’s a history of failures. Frameworks come and go. Today’s JavaScript frameworks are all very young. Backbone, Angular, and Ember may be trendy now, but not necessarily in a few years’ time.

Let’s look at Google Trends for Angular (blue), Backbone (yellow) and Ember (red) (2):

JavaScript Framework trends

JavaScript is the most popular programming language in the world, and allows multiple programming styles. Things are changing at an incredible speed. As a result the angry framework communities constantly fight over the best way to build an application.

And there is no best way.

There are a lot of different ways instead. Now Angular is in tremendous rise. “AngularJS lets you extend HTML vocabulary for your application.” Is that the best way? Are Backbone and Ember in a risky position? The companies that invested in Framework X in 2012 may soon realize that their development team is already talking about the next big thing. As a developer using one of these frameworks, I’d worry about their life expectancy.

On the other hand, let’s compare jQuery with Angular (3):

jQuery vs Angular

This gives you a good idea of the popularity of jQuery. It’s currently being used on 57.2% of all websites in the world and 92.7% of all the websites whose JavaScript library is known. (4) There is no technology lock-in. As an embedded application we cannot expect people to load another framework on their site but jQuery is there already.

Moot uses all parts of jQuery, I even borrow ideas from jQuery when designing an API. It’s simple and it works. I (still) love the beauty of it.

Why not Angular?

Angular looks promising. The fact that I can just write my model in plain JavaScript and let angular render the views without any glue code sounds awesome! But there are certainly things that I don’t like about this framework.

First, it’s about the same size as Moot as a whole (91kb). I want two-way binding only, but I’m forced to take the whole framework. There is too much overhead for me. I hope they will make the data-binding a separate piece and make it simpler. People shouldn’t need to worry about the internal mechanisms such as $watch, $apply or $digest.

And despite it’s been marketed as being simple, the API is huge. Currently there are 147 different sections on the sidebar of their documentation area. That’s a big cognitive load. I need an empty table for building stuff.

And I really don’t like to put so much logic in views or wrap my precious code to proprietary “directives” or “filters”. The fairly complex logic of Moot is better expressed with plain old JavaScript.

Why not Ember.js?

Ember is huge. I mean HUGE! The minified size of the library is 240kb. Needless to say their API is huge too. I picked the first section from the sidebar of their documentation (Modules > Ember) and that section only had 80 different subsections.

The biggest turndown, however, is that I need to wrap my handcrafted objects with Ember.Objectcausing the API to explode with new methods.

A big framework with a lot of proprietary idioms is a risky choice. Remember Enterprise Java Beans?

Why not Backbone.js?

Backbone is the smallest and simplest of the three frameworks, 33.9kb when minified. That includes underscore.js which is a hard dependency. More than half of the size of the whole Moot application.

My issue with Backbone is that I never liked the “backbone way” of structuring code. There is too much of boilerplate. I prefer the code to be compact. I completely agree that it’s important to separate the API code from the UI code but Kim Joar Bekkelund’s popular article (5) about turning your jQuery code into Backbone makes no sense to me. For me the resulting code is actually harder to follow.

And just like Ember, Backbone does not promote the use of POJO’s, so you need to wrap your objects with Backbone.Model.extend, introducing unnecessary framework-specific methods.

From the three Backbone is the least risky choice. It’s not doing any magic and even if its development stops it could be patched or replaced with your own wrapper.

Finally, as a RESTful framework, it’s not a perfect fit for real-time communication.

Scrapped frameworks

But jQuery leads to spaghetti, right?

Common thesis is that after you’ve piled your application with thousands of lines a jQuery hell will break loose. The application has no structure and the code is a large plate of spaghetti. This is simply not true. When API is fully separated from the rest of the code, it’s easy to build the controller code with jQuery.

Basically my controller code looks like this:

// controller for a Topic model
function drawTopic(topic) {
 
   // generate new element with micro templating
   var root = tmpl("<div>some html</div>", topic);
 
   // topic elements
   var seed_post = $(".seed", root),
      replies = $(".replies", root);
 

   // listen to events on model
   topic.expand(function() {
      // do something with the elements
 
   }).collapse(function() {
      // do something else
 
   }).remove(function(post) {
      // etc
 
   }).reply(function(post) {
 
   })...
 
}

 

That’s how I personally want my code to be organized. Goals for a web application should not be in imperative DOM manipulation, object oriented practices, or in “pure” MVC. A successful application aims to be simple, and there is no room for academic jargon.

The results

As a result of our combined perfectionism and minimalism, Moot is an extremely lightweight, manageable, and independent web application sitting on top of your page’s html. With the same “from-scratch” approach applied to our server side code and UX, it is not likely that you’ll see comparable discussion platforms very soon — unless groups of highly capable and relentless people already got the same idea some years ago.

 

Next blog entry: Riot.js – the “1kb MVP library” behind the Moot client.

Edits (Dec 7, 2013)

  • Updated Google Trends graphs
  • Updated file sizes and jQuery usage statistics
  • Added link to the Riot.js blog entry