Category Archives: Javascript

Famo.us – Scrollview

Famo.us

I really like the look of Famo.us, I just haven’t had the time to play with it much. I had some time today, and thought I should wait no longer! Having already done the tutorials on the Famo.us University pages, I thought I’d try and tackle some more practical problems.

Scrollview

When making mobile applications, the scrollview is ubiquitous. This is a UI widget that shows up everywhere and has so many uses. Luckily Famo.us has a an example in their Starter Kit. Download it from their home page.

The scrollview example is located in reference-examples/views/scrollview.

Take a look at the example itself. The code looks pretty simple, if you’ve gone through the University Tutorials, you should recognize many of the features. Open the example in a browser and test it. Just a set of colored rows with a single line of text. The scrollview doesn’t scroll with a click and drag. It does scroll with a swipe on the track pad. This doesn’t look like it’s doing anything, or is it? Try it in the iOS simulator, or on your mobile device. Here it scrolls with a swipe as expected.

Screen Shot 2014-09-19 at 12.10.43 PM

Take a look at the files in the example folder. There are really two files:

  • index.html
  • src/main.js

Looking at index.html you will see that there is not a whole lot there. There are a few links to js files, that are commented as “Shims for backwards compatibility.” I’ll guess these are not necessary for modern browsers. Then there is a section commented as “famous.” I’ll take a guess that this is the main famous stuff. This section has two style sheets and two js scripts. The first script loads famous from the famous CDN. While the second script loads “src/main.js”, which is the example js.

Take a look at main.js. Overall this is pretty short. The code is wrapped in a define() block. The function passed to define must be called when the rest of the famous and the DOM is loaded. Here require() is used to load modules of the famous code base.

  • Engine
  • Surface
  • Scrollview

After the requires, a context is created, mainContext. The context is the container that renders surfaces.

Next is a new Scrollview object is created.

Then a an empty array, surfaces, is defined. The array is passed to the scrollview object via sequenceFrom().

A note on scrollviews. In general these are set up to display items from a list, or array. The scrollview only displays the rows that are currently visible. If you have a list containing thousands of items, I imagine your iTunes library has thousands of items, your mobile computer does not have enough memory to display all of these as one giant list. Instead the the computer displays only the rows that are currently visible on the screen. I’m guessing Famous is using the same strategy. Hence it needs a list of surfaces to display. The scrollview will mange displaying these surfaces.

Next there is a for loop that builds surfaces and adds them to the surfaces array. Each surface is created with newSurface(). The content of a surface will be the text: “Surface: #”, where # is the number of the surface. The width is undefined, I’ll guess this allows the surface to be any width, and the height is 200 px. Next the surface is assigned properties. The background color, line height, and text align. These are standard CSS properties.

Each new surface was created in a local variable named temp. Next we’re calling the pipe() method and passing a reference to the scrollview. I’m not sure what this doing, I’ll have to revisit the Famous University.

Next push each new surface into the surfaces array.

Last, add the scrollview to the mainContext with add().

What next?

The best way to understand how these things work, and to develop ideas as to how you can use them for your own projects is to experiment! The best way to test these things is to start small. Making small changes and testing to observe the results.

As a start lets work with the content. Line 52 shows:

This seems to be the content of each row in the scrollview. Let’s play with this and test that assumption. Change the content, try making these changes:

  • Change the text
  • Add HTML tags to format the text

Next change the size of the rows. As is each row 200 px tall, note that the content has a line height 200 px which places the text in the vertical center, and also makes the text take up the whole height of the row.

Change the line height to something more smaller. Add a second line of content to each row.

Try out these properties:

  • fontFamily, fontSize, color
  • border, borderTop

Customize row content

The tableview is not very useful if you can’t customize the content of each row. In the example, rows are generated within a loop, and the only real content is the row number.

Make an array to mock up some more relevant content. The demo uses a loop:

Try replacing this with an array. Define an array and then loop through the array:

With this you should see the same rows, but only as many rows as you have elements in the array. Now display the content from the array. Find where the content property is set for the surface. Try this:

At this point you should see something like: “Surface: A 0″ for each row. You can use HTML and CSS in here also. Imagine this:

Add a class name. You’ll need to style this class in your style sheet.

Watch the quotes carefully. Attribute values must always be in quotes. Since the outer quote is a double “, the inner quotes need to be single ‘.

Adjust the height of the cell.

The example adds a few properties like:

These these generate CSS properties that are attached to the row element as inline styles. Prove this to yourself. Use the inspector to view one of the scrollview cell rows. You should see something like:

This shows each row is displayed from a div with a famous class, and some style properties. Some of the properties are applied by famous, while others were added by us when the surface was created.

I think it’s probably better to move our styles to a style sheet. At this point it’s hard to say if this is best practice for Famous. In any regular HTML page it would definitely be best practice.

Note that the color value is generated for each row, the value is based on the row number. It’s this system that gives us the great rainbow effect. For styles that need to be generated on the fly based on data only available when the surface element is created, setting the properties here is a good idea. For general properties, I’m guessing it will better to use a style sheet.

 

 

 

 

 

 

HTML5 is there yet?

Here are some thoughts on HTML5 and whether it’s up to the task of making mobile apps.

Mobile browsers lag, so mobile HTML5 apps suffer

This article from principal HTML5 evangelist at Mozzilla. He says browsers are not up to the task. This is coming from someone at a company that makes browsers. He’s saying the browsers don’t do enough to satisfy the vision that everyone has for HTML5. I have to ask is that a problem of the browser really? Is this a case where someone is saying “hey your browser needs to live up to my vision.”

He also says:

HTML5 is a recognized as a set of standards-based specifications for so-called modern Web applications with multimedia capabilities, leveraging JavaScript and Cascading Style Sheets.

After reading this I had to ask. Is a web browser with multimedia capabilities really the platform to deliver full feature mobile applications?

Here’s another article

Forrester: HTML5 apps still not as good as native apps

Here is a quote:

But adopting HTML5 for mobile apps isn’t a panacea, as reflected in Forrester’s findings. In fact, one of the report’s survey responses noted that 59 percent of the time, apps developed solely using HTML5 took longer to deliver than planned. With non-native responsive frameworks, the greatest amount of time was lost testing and fixing issues.

The survey of developers says 59% of the time HTML5 apps took longer to develop.That flies in the face what people have been touting as common wisdom for the last few years. It seems to fit with my limited personal experience.

Here’s another survey:

Mobile app development: 94% of software developers bet on HTML5 winning

This survey from 2012 says an overwhelming percentage of developers are planning to use HTML5 to build their apps. Their top reason: familiarity with the languages HTML/CSS/JS. I have to ask is that the right reasoning? Admittedly the second most popular reason was cross platform compatibility. You can only imagine that wanting building apps in HTML5 since it is more familiar means that these people do not want to spend time learning a native development tool, and they thought it would be faster and easier. In the article above, from 2014, two years later, shows that a majority of developers agree that it took longer to develop their apps in HTML5. I can imagine that a fair amount of apps took just as long it would have taken to develop native. A few may have been developed faster. But for the majority it was longer or about the same, to develop an app that will lower performance than a native app.

Not sure this looks like it may have come from the same survey above, but doesn’t appear in that article:

Survey: Most Developers Now Prefer HTML5 For Cross-Platform Development

Again here they show 90% of developers using HTML5. I work with students developing apps, and many students want to use HTML5. Many for the reasons popular in the article above, ease and familiarity. I would say a majority of the projects are social media. Notice the chart here labeled types of apps. The most popular app is productivity at 54%, social media apps is 18%.

You could say that social there are fewer people developing social media, and that may be true, it’s hard to say from this chart. Look at games only 8%. Games have to be in the top three for shear volume in apps. Social media apps are also very popular. Looking at the chart in this light, you might start to think that people are choosing native for games and social media. Obviously you can’t make a definitive conclusion like this from this information, but it does hint that there is more to this than the 90% figure.

Also note that the survey was conducted by Telerik kendo UI who develop an HTML5 mobile framework. Some of the questions skew in the favor HTML5 like:

  • Only 15% of the more than 5,000 surveyed would use “Native-only” to target multiple platforms

Targeting multiple platforms with native is native’s biggest disadvantage.

I went out on a limb earlier and said that native apps had better performance. What does that mean?

Americans Prefer Native Mobile Apps Over HTML: Survey

This survey says people prefer native apps. Here’s a quote:

“Smartphone home screens across the country are littered with the tombstones of mediocre, try-once-and-forget apps,” Joseph Farrell, executive vice president of operations at Bite Interactive, said in a statement. “Brands and developers too often lose sight of the most important aspects of developing mobile applications: build in-brand, powerful and highly usable apps that continually deliver real value to your users by solving the problem they have asked you to solve. Delivering continued, iterative and brilliantly executed solutions to those evolving problems should always be the primary objective.”

I think this is a good point. Developing an app faster (or may be not faster) for less, is this a good thing when the user experience is poor? Did you really save time and money? Was your time and money well spent? Maybe not.

From a user perspective native is better. From a developer perspective HTML5 seems to be preferred. Think about that for a moment. Is this the cart driving the horse? shouldn’t a developer want to produce the app that will provide the best experience and performance for a user? Seems like there is little advantage in choosing to develop an app in HTML5 because you are familiar with it, rather than it is the best tool for the job.

But wait, there’s more. Here’s another.

Mobile app developers’ interest in HTML5 is slipping

Here’s an interesting paragraph:

This was the lowest level since Appcelerator began tracking the specification in April 2011. “Interest in HTML5 peaked in July 2012 at 72.7 percent and has shown and uneven but downward slope since,” the report said.

I think this is referring to the same survey that showed HTML5 down to 59%. They mention a downward trend. There isn’t a chart or reference to this, which is too bad. It should be noted, that the survey mentioned here is from Appcelerator, which is a JS based pseudo native app development tool.

Here’s a quote from another source:

In the battle between HTML5 and native apps, HTML5 is starting to become a strong contender. While native app approaches have been a top choice in the past, a recent survey revealed that 57% of participants believe HTML5 is enterprise-ready, or will be in within the next year.

I have been hearing this for a few years now. Note the article was from 2013. We’re in the fourth quarter of 2014, and I think it’s still debatable if HTML5 is “enterprise ready.”

Seems the real advantage to HTML5 for mobile apps is, that it is faster and easier to develop. Keep in mind that the earlier survey said 59% of developers thought it took longer to develop in HTML. Users also prefer native. In this light the advantages of HTML5 seem very slim to nonexistent.

Why post this? I don’t have an axe to grind, but I do feel there is a lot of hype in HTML5 these days. And it’s easy to see it as a good fit for everything. I feel this approach is not the correct approach. Without applying an honest critique to what is happening in the real world you run the risk of choosing a tool that is not the best fit the job. Which leaves you with a poorly performing product and more hassle than necessary. I believe there is a class of app that works well with HTML5, but it’s a small subset of all of the apps you could make. I also believe that the margin in development effort between native HTML5 much slimmer than what most people would suggest, and possibly nonexistent. If there is an advantage to HTML5, it’s in distribution.

 

 

Screen Shot 2014-01-05 at 11.56.51 PM

WordPress – jQuery

WordPress will load jQuery automatically without you having to add the files yourself. I’ve seen a different methods, some of which do not always work. Here’s the method I use that seems to work reliably.

The following would be added to your functions.php file. If you don’t have a functions.php yet, create one, in your theme folder.

 

 

Note! There can be no characters, this include spaces, or extra lines, in front of the tag. This is good practice. Extra characters outside of the php tag will cause the server to create HTTP header and send it to the browser before WordPress is ready.

If you already have a funtions.php file in your theme, you can add the snippet above, without the <?php.

WordPress loads jQuery in “No Conflict” mode. This means that jQuery will be accessed through the variable jQuery rather than the $. To work with this easily, set up your document ready actions like this:

Notice here, that jQuery (note the uppercase Q!) replaces the $ outisde the ready function. While inside the function I’ve used the $. This is possible by including the $ as a parameter to the function inside jQuery(function($){}). Placing this variable here allows jQuery to assign itself to this name, so inside of the function you can use that variable in place of jQuery.

Famo.us

Famo.us is a new JS library that is a very cool and inspiring. From my cursory investigation I’ll present my thoughts on Famo.us.

The goal of Famo.us is to create a graphical engine that renders elements to the browser more efficiently than current techniques. At the present time browsers are designed to render documents, rather than graphical elements, this presents a lot of bottle necks. Famo.us converts the typical HTML document type content into graphical elements, and renders them to the browser using canvas and webGL. This evolves the process of creating web apps from an experience of wrestling with HTML/CSS/JS to make something that mimics an app-like appearance. To, something more akin to making real apps.

There is something very different and distinct about using Famo.us. Rather than creating a web page with it’s DOM, and styles, and relying on the browser to position content based on a long list of arcane (and, should I add twisted) rules, is very different from freely placing things on the screen using x, y, and z coordinates. With Famo.us you are creating graphical elements that live in a 3 dimensional space on the screen. These elements can be freely translated and transformed.

The bigger promise of Famo.us is to create templates for apps that anyone can apply to their content. Much in the way that themes are applied to WordPress content. Realizing this goal would create an explosion of HTML5 apps, and make good on real the promise of HTML5, which at the current time has not lived up to it’s hype. All of these templates would be using the Famo.us system to position, and animate elements close to native rendering speed.

Here are a few basic concepts. To display things with Famo.us you need a Context and a renderable. A context is an area where one or more renderables can be drawn. A renderable maps to a display element in your page. A page can contain more than one context, or the context can take up the entire page.

The basic renderable is called a Surface. A Surface can contain HTML content, and is styled with CSS rules. You can set styles via JS when creating a new surface. Surfaces then become the basic view elements containing your content that are rendered to a Context. Imagine buttons, text boxes, and images all as Surfaces moving around a 3d environment in the browser window. Neat!

Famo.us looks pretty cool. I’m going to call it a second generation JS tool kit. Like AngularJS, it moves beyond the previous tools and sets new paradigms and increases the performance of web apps. If you were a Flash developer, and long for the days when you could do all of the things people were doing with Flash in the browser, I feel that this is the tool that will get you excited again. I can definitely see showcase web sites, like FWA, popping up to show Famo.us work.

All of that’s pretty rosy so I’ll end with a word of caution. Browser based apps are still hampered by downloads. Every file asset must be downloaded and cached. Ever been browsing a page when the style sheet did not load? Browser based apps built with Famo.us will still be prone to these issues. On desktops with a fast connection, the issues are minor. On mobile devices with slower connections these issues will be more apparent.

Native or HTML5?

Native or HTML5?

Starting a new project, you’re likely to explore what would be the correct platform as a first step. Javascript has a lot of buzz right now. There seems to be a movement to do everything in the Javascript language. At the moment you can Write your app with JS, script your server with Node.js, query your data base in JS using MongoDB. Wow, sounds like you can do it all in JS! This is neat but, I feel it’s important to not lose sight of the forest through the trees. In any project it’s really about choosing the right tool for the job.

If we’re doing everything in JS does that mean the browser is the new OS? I don’t think so. There’s a bit of the emperors new clothes in this type of thinking. The thing about JS and apps in the browser is they just don’t live up the promise in many cases. Or, maybe I should say that there is to much promise. JS has a lot of hiccups and performance issues. Writing a program across HTML, CSS, and JS has a lack of elegance, and feels crude and verbose at times. Just because you can do something doesn’t mean you should. Again it’s about choosing the right tool. The big draw of JS for everything is that it leverages a common tool set, on a common platform. This can save time and money which is good, but if you are making an inferior product is it worth it?

I don’t want to sound like I have some axe to grind. I’ve had a lot of fun with JS, and if it’s the right tool for the job I’m more than happy to use it. My point is HTML5 has so much hype people are treating it like it can do no wrong, like its the wunderkind that can do anything. I just want to get real here. JS can do anything, and I suppose that’s a really a great thing. But, just like people, JS is good at somethings and not good at other things. I’m a firm believer that anyone can do anything if they put their mind to it, I’m not saying that everyone can break world records.

There’s a lot to like about writing code in one place using a common set of tools and deploying to every platform. But if the app provides weak and compromised user experience do you want to put your name on it? Look at Facebook. They had an HTML5 app, and the user experience and performance was weak. The way I see it, they essentially shoehorned a web site into an “app”. They obviously bought into the promise of HTML5.

“The biggest mistake we’ve made as a company was betting on HTML5 over native”

M Zuckerberg

It’s fun to think you can recreate all of the nifty transitions and animation of a native app with JS in a browser. But, you’re not really doing your job unless you apply a critical eye and are willing to say that something is falling short of expectation. Kudos to Facebook for owning up to a problem that was theirs.

Is the browser the new OS? Computers are getting faster, and JS can do more in the browser than ever before. But I don’t think this makes JS the be all end all. There will always be something you can do native that will be out of reach from the browser. Either for security, performance or other reasons. The world may spend more time in a browser than all other apps combined but, I don’t want to edit images in Safari, and I don’t think this is where the world is going.

 

 

AngularJS – intro

AngularJS is a Javascript framework from Google. It’s goal is to display data in a web page based on the MVC, and related paradigms. It was built with the idea of being able to make the connections between, data and UI, apparent and easy to manage.

I just began with it a day ago, so take everything here with a grain of salt. I’m sure I’ll cringe at this a month from now. I’m just writing this all down to try and get it all straight in my own head.

Directives

Directives are attributes, that act as hooks for AngularJS. Assigning a Directive to a tag creates link to that tag and it’s contents to AngularJS.

AngularJS defines many built in Directives. These all begin with ng-. For example, ng-app, and ng-model. These can, optionally, be prepended with data- for validation if you like. For example: data-ng-app, and data-ng-model.

You can also write your own Directives.

Here area  few Directives.

The ng-app directive tells Angular which part of the page it should manage. It could be placed in the html tag to manage the entire page, or on the body or div tag to manage a smaller realm.

Where this tag is placed determines the document root for Angular. Placing the ng-app directive on a tag other than the <html> tag will limit the scope of the Angular app to that region of the page.

Include an optional module name as a value to this attribute. For example: ng-app=”moduleName”.

The ng-init Directive initializes data. Usually you’ll want to handle this with a Controller.

The ng-controller directive attaches a controller to DOM element. A controller is a Javascript object that will manage data displayed in that region.

The ng-repeat directive tells Angular to copy the elements within the repeat element a number of times. It will populate this “template” element with data from the model.

Within ng-repeat Angular defines $index, $first, $middle, and $last. $index holds the the index of the repeated element. While $first, $middle and $last are booleans, true when the element is the first, middle or last element.

The {{}} defines a template expression. The {{ and }} can thought of as defining the area where Angular will write data. The expression inside can be thought of as modifying or defining how the data is written.

The ng-model attribute allows you to define connection from the DOM to model data. In the case of an input field modifying the input modifies the model data directly.

The | defines a filter to be applied to the content of a {{}} template. There are several built in templates, and you can define your own. The example above formats item.price as currency.

The ng-click directive sets up a click action that will call on JS we define. The handler function should be part of the $scope of the controller that contains this ng-click.

Note that $index is a variable defined by ng-repeat.

The ng-bind attribute can be used to bind a view element to a model value. This works the same as use the {{}} template syntax. Where the {{}} syntax will show the {{}} for a moment when the page initially loads the ng-bind directive will not. Making this good for elements that will show initially.

Use ng-change to call a function defined in the $scope of the elements controller when a form element changes.

Use ng-submit to call a function when a form is submitted.

Images and Anchors are special cases and have their own specific directives.

MVC – Model View Controller

MVC is a software design pattern that breaks functionality into three areas: Model, View, and Controller. This pattern is particularly suited to software that handles and manipulates data via user interface. Which makes it a good fit for Web apps. AngularJS turns HTML, CSS, and Javascript into a surprisingly good fit for this pattern.

Models

Angular uses the MVC, or Model, View, Controller, paradigm. Where the Model represents data used by your program. For example, a list of user names, or a list of products with their price and description. The View is where data is displayed and represents the visual end of your program. The controller is the business side of your program. It contains the logic that manages data and facilitates translating data so it can be displayed by the View.

A Model can be as simple as a variable containing the number of times a button has been clicked. More often model data will be an array or object containing a list of values and properties.

A Controller might contain functions that controls the how a number is displayed. It might round the value off or format it any number of ways. More often the Controller will load an array of data and sort and filter before sending it to the View.

Views in Angular, are HTML. The view is essentially written in HTML and CSS, along with Angular’s templating system. Controllers are tied to views directly in the HTML as attribute names. This is a key feature of Angular that makes it unique.

Controllers

Controllers handle processing model data.

Views

The display data held by the model. Views in AngularJS are templates defined as snippets of HTML. These can be external files loaded into the app, or defined within the same file tags. Templates can all be defined as strings as part of a controller, directive or other module.

Modules

Model data should be defined in a “modules”. Use Angular’s module method to create a new module.

Services

Services are singleton objects that provide global functionality to an app. Built in services begin with the $, such as $routeProvider, and $http.

Bootstrapping

Here’s the outline for an Angular page:

Use the ng-app directive in the HTML tag to declare everything in your document as part of the “app”. Load the Angular.js file at the bottom of the body tag to improve load times.

Templates and {{}}

Templates define the views your app displays. Templates are written as plain HTML with the addition of the {{ and }}. Expressions and references to model data are placed inside the {{ and }} to determine where that data will be displayed in a template view.

Templates can be defined as external html files, or tags written in the host file.

 Expressions

Expressions are Javascript like snippets of code that can be placed in the HTML of your page. Usually they fall inside of the template {{expression}} “tag”. But they can also be declared as part of a directive. Expressions support a lot of basic javascript but not everything.

Angular expressions are evaluated against the current $scope.

Angular expressions do not support loops and flow control like if statements.

Angular expressions are not parsed using JS eval(). Instead they are parsed using Angular’s special parsing function. This means that expressions that fail produce no output rather than an error or undefined.

Filters

Web apps revolve around text and data. Which often needs to be formatted in may different ways. AngularJS provides filters for this. Filters can be used in Angular expressions to perform formatting tasks.

Since expressions can be used directly inside templates it makes a nice works flow as you’ll be formatting model data in the same place it will appear in a view.

Follow and expression with the | and the name of a filter to apply the filter to a value of the expression.

Forms

Angular is really great with forms and handles them natively. Angular provides built in form validations service. Model data can be tied directly to the value of form elements. This is a two way binding. That is a changing the value in a form element, typing into a field instance, will update the Model, and updating the value in the Model will change the value that appears in it’s asscociated form element.

AngularJS provides many directives that apply directly to form elements. Here are three:

  • required
  • ng-maxlength
  • ng-minlength

Add a controller to a form to handle validation. Angular provides $valid, a boolean, which represents the validation state of the form.

Assigning model data as values for form elements means the form data is accessible in your controllers through the model.

Data binding

Data binding in Angular is two way. Any View element that is bound to Model data will show the current value at all times. If the value in the Model changes the view updates, if the value changes via the View, in the case a of a form element, the value stored in the Model changes also.

Dependency Injection

Dependency injection is a system of sharing services with modules. Essentially, from what I’ve gathered so far, and knowledge is limited at this point, dependency injection is boils down to sending a reference to a service as a parameter to a controller function.

Most of the information here was gleaned from AngularJS By Brad Green, Shyam Seshadri Publisher: O’Reilly Press. Get at the library