Backbone Requires a Main View for the App?

Tuesday, December 27, 2011

Here's a continuation of time spent considering my previous problem: Backbone.js and its view-centric MVC architecture.

Would we really want a model to be able to render itself to the page? Considering the information it has, I don't think we want it to. First of all, how does it know where in the DOM to draw itself? I suppose we could give it a specific DOM element as an attribute when create the model, then it would know where to draw itself. But, what if this model is in a collection, such as a list? How does it know where in the list to render? We could probably wrestle through this problem, but the code would get mangled somewhat, and each model instance would get pretty heavy.

It seems, then, that this task of rendering a model is best performed by either the model's collection or its view. In other MVC frameworks, a 'controller' is used to place the model's information in the view's DOM. In backbone, this is the responsibility of the 'View' object. Why is it called View instead of Controller? I believe it was named this way because it is meant to 'resolve to' HTML code. Not a name that suits the MVC style, but I can see the logic.

A Backbone app, then, requires a main view (controller) that spawns views and models, using these views and models purely for code organization's sake, delegating to them solely the task of data integrity. I started hacking at my backbone app thinking that the main view's (controller's) job is just to initialize everything, but this is not the case. Instead, it is in charge of creating and destroying the various Views and Models in your app and associating models with views.
(Still not sure of the recommended relationships between views and models. I'll have to keep reading stackoverflow's backbone tag responses to learn more.)

I'm starting to think that this framework is overkill for what I'm trying to do. Something like knockout.js seems like a smarter choice. I've heard the developer say that it is great for creating "JSON editors". That is, request JSON from the server, then bind its attributes to fields for easy editing. That is also on my list of libraries to try.

What SHOULD MVC be for Javascript? Towards other JS MVC ideas.

Saturday, December 24, 2011

With all the trouble I've been having with Backbone.js lately, I've decided to take a step back and look at my attempts from a higher level. Using a framework shouldn't be this difficult! Why, then, am I having so much difficulty? I've decided that it is because my idea of "Javascript's version of MVC" is misbased. Therefore, I've decided to start looking at the whole spectrum of Javascript frameworks - Backbone, Spine, Knockout, and JavascriptMVC (did I miss any other major ones?).

Addy Osmani (not quite sure why he's famous, but he's skilled at explaining these frameworks from a high-level) recommends JavascriptMVC, because it is the "most comprehensive" and mature framework at the moment. I hope the community is friendly, because I've decided to choose this as the next stepping stone in my Javascript MVC studies. I hope the people that created it were educated enough to use intuitive object names and abstractions, as I'll need them to improve my understanding.

When reading this introduction to JavascriptMVC, I've been inspired to return to the idea of an application's "state" once again. The author asserts that "The secret to building large apps is NEVER build large apps. Break up your applications into small pieces. Then, assemble those testable, bite-sized pieces into your big application." A agree completely with this! But, how can one make bite-sized Javascript pieces? Inevitably, these pieces must talk to each other, so how can we do this?

How about this idea for communicating between modules: Use the page's state variables to communicate between these pieces in a pub-sub manner. This manner is very much like how disparate computer systems communicate across the internet. The internet is probably the most modular system I am aware of, and if modularity is what you want, then using the internet's model is probably best.

So, the page's state. Would having a set of variables on your web page limit the scalability of your site? As long as you aren't transferring the state back to the server, you should be fine. As long as the web app talks back to your servers through a stateless API, you should be fine.

Great, so I can't think of any reason why we can't have a few state variables on our client-side page, so I'll try to use the state to facilitate communication between Javascript components. (If it is easy to do with JavascriptMVC that is.)

Backbone's Perverted Architecture and MVC

Sunday, December 18, 2011

I'm still working on getting my Backbone.js project to work. So far, I've got a text box and a list that would update itself. Not too impressive. Why am I not successful? Three reasons: (1) I've never worked in Javascript before, (2) I haven't used this framework before, and (3) I haven't used this perverted style of MVC development before.

Perverted style of MVC? Yes, Backbone doesn't tell you how to use its objects, it feels like it is saying
"Here's 3-4 Javascript objects that we like. They work great together! They have built-in behavior, which makes it awesome! However, there's a lot that ISN'T built-in, and we leave that to you to figure out. But this is what makes Backbone flexible! Great, isn't it?"

Some questions I find myself asking: How should I structure my JS app? View-centric, model-centric, or collection-centric? I would like to just manage the Javascript side of the app - just worrying about the collections or models. If I add a new model to a collection, it should automatically render the change collection to the page. I have found no examples for a model-centric app like this. I find myself with a machete in a jungle, hacking my through the objects and their relationships, trying to find the path that the Backbone designer has left for me to find.

Looking through the Stackoverflow questions and answers, it seems that it is possible to create view-only apps with Backbone. This confirms my suspicion that I've been using Backbone in a backwards way, trying to create my models first. One thing I learned today is that the idea of a Backbone View is that it 'resolves' to an HTML tree that can be applied to the page's DOM. That is, your master 'AppView' is meant to create sub-views, then  request their HTML rendering to apply onto the page. Frick! This makes no sense! So the view can't actually render itself on the page? It requires a parent view to place it in the correct place? No! Maybe if I understood the capabilities of Javascript a bit better, I could make Backbone do it this way, but I was not successful.

Next time I try to fix this app, I'll take the view-centric approach. I'll have my master AppView spawn child views, then pass them a model to hold its data. It's a very silly way of approaching the problem, but I'll do it. I'll do it just to see if backbone actually works with Visualforce. Then, I'll look into optimizing the architecture, unless I move onto a better JS MVC framework.

Since I've been taking this 'backwards' model-centric approach, I'll change gears when I stab at this project next. That will work, for sure. Then, I'll try using Spine.js, which looks like it has a much more sane architecture. Also, Spine is appealing because client interactions are completely decoupled from the server, which sounds like the ideal remedy for the slow response times between Visualforce pages and their Salesforce servers.

Initial Backbone.js on Force.com Issues

Thursday, December 15, 2011

I spent a fair amount of time the last day or two working on creating a Visualforce page that uses backbone.js as an intermediary for communicating with the Apex controller via Ajax calls. I am still doubtful whether this framework will prove to be a good way to interface with Salesforce objects and data, but I won't know until I finish.

Now, much of the time I've spent so far has been to connect the several backbone.js objects. They are: the model, the view, the controller, the HTML templates, and their duties to one another.

While backbone.js is a framework that follows the MVC pattern, backbone's view serves a different purpose than the view in other frameworks, such as Salesforce's own MVC framework of Visualforce and Apex. The purpose of Backbone's view is to bind to an HTML element, and, when appropriate, render data from the model into this element using an HTML template.

Did you also notice the interesting bit here? There are actually two views in play here! The HTML is the true (or truer) view, while the backbone.js view supplies the HTML view with logic, acting almost like a controller.
So if the view is a controller in backbone.js, then what is the controller? Well, in backbone.js, the C represents collection, which is a "smart list" that holds backbone models. Likewise, backbone models are simply Javascript objects, nothing more!

Well, that's a slight simplification, since each of these backbone objects has a bit more responsibility than I explained above. I'll explain the jobs/responsibilities of each of these backbone.js objects in my next post. For now, I want to discuss a few of the issues I've encountered.

The first problem I was having was with jQuery. It is usually necessary to use jQuery in no-conflict mode, and to alias it to a variable that is not '$', such as '$j'. Having said that, Backbone has two other Javascript libraries as dependencies, Underscore.js and jQuery, and uses them extensively under the covers. I had some problems with using no-conflict mode here, but this was solved with a few well-known tricks. Here is one way to solve the problem. This great blog post has some other solutions.

j$ = jQuery.noConflict();
j$(document).ready(function($){ /* All Backbone code goes here, called after onReady is fired. */ });


The other problem is that Backbone.js is built to use a RESTful way of GETting data from and POSTing data to the server. So naturally, I started writing a @RestResource class that will respond to these calls to retrieve data and update data in the database. This is one place I started to encounter problems - these REST handlers are located at na4.salesforce.com/services/apexrest/, which is a cross-site-request from the Visualforce page at c.na4.visual.force.com/apex/. Still not positive this is the problem, but I'm pretty sure. To resolve this, I will attempt to handle Backbone's sync calls with Javascript Remoting.

Backbone.js and AUI on Force.com - Good Idea?

Web development is an art. It is easy to make a web page, but very difficult to make a beautiful one. It is easy to make a static page, but very difficult to make a dynamic one. It is easy to make a site with multiple pages, but very difficult to make the content intuitive and interesting to navigate. A page I make may be perfect, but a friend may look at it and dislike it, or more ideally, be able to offer constructive criticisms about it.

Because web development it is such an art form, it matures over the years. In the early days, there were single page sites. Then came multiple page sites, followed by interactive/dynamic sites, and as they matured and became more user- and data-centric, became full-fledged web apps. All these changes were enabled by a maturing culture among web developers, new technology and languages, and a shifting market for consumers of the web sites and web applications.

Some web apps are data-centric, such as most apps on the platform with which I work, Force.com. What I dislike about the platform, however, is the length of time it takes for requests to return from the server and for the page to refresh. When I came across the idea of the Asynchronous User Interfaces for web sites, I fell in love with the idea. This is how a web site UI *should* feel. It feels fast like a native application while still allowing me to dynamically manipulate and synchronize data with the backend.

So why, then, are more people not making AUI web sites? I can understand if it was much more difficult, but with the right abstractions, it seems to be not too difficult at all. Choosing a simple library, such as backbone.js, spine.js, or knockout.js can make development on one of these one-page-sites much easier.

I want to give a high-level overview about how a tool like backbone.js could be used on top of the Force.com platform. Let's take a look at the building blocks we have. Force.com is the server-side database. The methods on the Apex controller is the intermediary between the client-side web page and the database. Then we have the client-side web page, which is HTML/CSS for the display and Javascript for the client-side logic.

What I want is an HTML table that is a view into a Javascript object collection. When I modify elements of the HTML table, I want the modifications to be directly modifying the Javascript object collection that is bound to it. Then, I want it to save to the Force.com database, either at random, appropriate times, or on-demand by clicking a save button. Let's see if we can make this happen.

I've have just a little experience with Javascript and web development, so I'm not sure if this is possible or a good idea, or even if it will be better than what exists. I'll find out soon enough.

Changing Object Functionality in OOP Languages

Sunday, December 11, 2011

A while ago, I had a conversation with a coworker about the maintainability of code and objects aspects of software craftsmanship. Suppose I make a method and think it's perfect. Inevitably, this method will have to change its functionality, probably due to change in requirements. In cases like this, how should one approach this refactoring? I just came across the concept of the "open-closed" principle, conceived way back in 1988.
en.m.wikipedia.org/wiki/Open/closed_principle
I originally was influenced by the idea of immutable data structures, mostly due to listening to Rich Hickey praising them in his talks on Clojure and it's concepts. Immutable data structures are interesting because they can be shared among different methods and threads safely. Immutability helps remove any surprises caused by method/function side effects. Though I haven't run into this problem before, it's a bit very attractive concept because it encourages simplicity in reading and maintaining existing code. Simplicity is king in the land of software development.
The open-closed principle, on the other hand, promotes simplicity in method/API design by promising to not change the API and its implementation. This reduces the chance of creating bugs in the callers of your methods. If the implementation of a unit of code must change, the open-closed principle instructs us to subclass and override the unit of code we wish to change. This sounds great and makes our code immutable, in a sense, but it seems to be forgetting about about another core principle of programming, which is the wonderful typing system.
This improvement/customization to the open-closed principle occurred in the 1990s, according to wikipedia. The revised version of the principle instructs us to use interfaces or abstract classes and create new implementations of them, rather than directly subclassing the class to change. This is a much better solution, as interfaces are a more precise manner of expressing functionality and purpose of an object.
It may be a challenge, and but we should remember to use the tools that our languages provide us. We should remember to use interfaces where appropriate.

The Base of Maintainable Programming Languages - Libraries over Syntax?

Tuesday, December 6, 2011

I often wonder about what language is "the best". It's fun to think about these things theoretically.

I believe that there are two relevant ways of expressing meaning in a language: syntax, idioms, and libraries. Syntax is direct meaning and the compiler won't let you write bad syntax. Idioms are common ways of using language features to solve common problems. Libraries solve big problems that requires lots of code, and abstract it into a simple interface, a new syntax.

Discussing just the library side of languages -
If a language has very powerful standard syntax, newbies will try to solve all of a language's problems with the language's standard syntactic tools. If a languages has fewer syntactic tools, then the newbie will be forced to either write lots of code to solve simple problems, or to dig into the language's community and common libraries to solve problems.

I argue that it is theoretically better to have a language with less complex syntax and a stronger community-maintained set of libraries that solve common problems. Such as Lisp/Clojure, where the language's entire functionality is constituted of its libraries. This way, if you attempt to solve a problem, you are reinventing very little, but rather, you are subscribing to an existing solution to the problem.

When others come to look at your code later on, they can see what solution you chose to subscribe to. Even better, your solution/library has a name attached to it, and that name can be Googled to find much more information about that solution on that library's website or IRC channel.