Sencha Touch container tap events!

Sencha Touch is awesome, but sometimes can be frustrating. Some components just don’t have the events that you need. For example you can’t add a tap listener for a container inside of your controller’s config. I know you can add a listener on the component in the view, but I hate doing this because it moves controller logic in your view.

How do you get a container to listen for a tap event?

Since the component doesn’t have a tap listener we can add one to the components element object! Attaching a listener to the component’s element object gives you access to pretty much any event you will need. In this demo I’m going to use the tap event.

The view with the container component

Ext.define("MainView", {
    extend: 'Ext.Container',
    xtype: "main",
    name: "MainView",
    config: {
        layout: {
            type: 'fit',
            align: 'center',
            pack: 'center'
        },
        items: [
           {
            xtype: 'container',
            items: [{
                xtype: 'container',
                name:'clickableContainer',
                html: 'Hello there click me!'
            }, {
                xtype: 'container',
                html: 'Not clickable'
            }]
        }]
    }
});

The controller

Ext.define('MainController', {
	extend: 'Ext.app.Controller',
	config: {
		
	    control: {
	        MainView:{
		    initialize:'init'
		},
            },
	    refs: {
		MainView:"container[name=clickableContainer]",
	    }
	},
	init:function () {
          var containerView = Ext.ComponentQuery.query('container[name=clickableContainer]')[0];
	  var containerViewEl = containerView.element;
          containerViewEl.on('tap', 
            function( event, node, options, eOpts ){
         	alert('clicked the container');
    	    }
          );
	}
});

First thing we do is set up an init method, which is where we get a reference to the container view. Once we have the container view we can get the component’s element and use the on method to set up a listener (you could substitute the onBefore or onAfter method here), and just like that we have a container with a tap event!

Pull to refresh UITableView | UIRefreshViewControl

I use UITableViews in almost every app I build, and sometimes I need to implement a pull to refresh like a boss. Its pretty easy so lets get started.

Adding a UIRefreshViewControl

Lets set up the scenario first. You have a storyboard with a view controller, and inside the view controller is the the UITableView that you want to add the UIRefreshViewControl to. You cannot add a UIRefreshViewControl in the storyboard so we will have to add it to our table view in the ViewController.

What if you don’t have a UITableViewController!

You can’t add a UiRefresViewControl directly to a UITableView so if you are inside a UIViewControlelr and only have tableview, you can just add one!

- (void)viewDidLoad
{
    [super viewDidLoad];

    UITableViewController *tableViewController = [[UITableViewController alloc] init];
    tableViewController.tableView = tweetsTableView;

    self.refreshControl = [[UIRefreshControl alloc] init];
    [self.refreshControl addTarget:self action:@selector(refreshTweets) forControlEvents:UIControlEventValueChanged];
    tableViewController.refreshControl = self.refreshControl;
    self.refreshControl.tintColor = [UIColor colorWithRed:(254/255.0) green:(153/255.0) blue:(0/255.0) alpha:1];

}

First we create the UITableViewController and set the UITableView from the storyboard as its tableview property. Next I alloc and init the refreshControl and add a target and action. This is the callback method when the tableview is pulled to refresh!

Hide the UIRefreshControl

- (void)refreshTweets{
    // refresh logic 
    //End refresh control
    [self.refreshControl endRefreshing];
}

The endRefreshing method removes the loading icon from the top of the TableView and we are back where we started with our TableView!

Build a scraper with php

There are a lot of ways to get data from websites, most of the time this is in the form of an API. When this isn’t available, you can build a scrapper to pull data right off of the website through its html.

When can you use a scraper?

Anytime you have access to html you can use a scraper to parse that information and gather the data you are looking for. The main issue with scrapers is you are relying on the structure of the page to be the same every time you send your script off to gather data.  This is why I’m weary about using scrapers as long term solution for data gathering.

Is PHP the only programming language to use with scrapers?

No,  you can pretty much use any programming language as long as it has the ability to pull in a web page’s content and parse the html that is returned. One thing to look for that is extremely helpfully is a pre built HTML dom parser. To find if the language you are using has one search “(programming language) html parser”  and you will find a ton of different options. I will be using http://sourceforge.net/projects/simplehtmldom/. A dom parser allows you to easily search through the returned html and find specific tags and the data contained within the tags. Now that we have a basic understanding of what tools we will be using lets get started!

Start Scraping!

Download this sample from github https://github.com/barrettbreshears/PHPTwitterScraper

Well actually lets hold off on that. Before we write any code I always like to get and idea of what the html structure looks like, and if there is a pattern or unique class or id I will be able to use to grab the data from the website. I will be using my twitter page for this demo https://twitter.com/BarrettBreshear and I will be grabbing all the tweets and when they were tweeted from the page. Also if you guys would like to follow me on twitter I would really appreciate it! Anyway when I inspect the page’s html I see that all the tweets are nested inside of an <ol> and each tweet is located inside of a <li> and all the tweet data is located inside of a div with the class .tweet!

Screen Shot 2014-02-11 at 10.29.30 PM

Now that we know the basic structure of the page lets get started scraping!

find('div.tweet');

// loop through each tweet div and pull out the timestamp and text
foreach ($tweets as $tweet) {
	$tweetText = $tweet->find('p.tweet-text', 0)->plaintext;
	$tweetDate = $tweet->find('a.tweet-timestamp', 0);
	echo $tweetText . " : " . $tweetDate->title . "\n";
}

 
Thats is! As you can see there really isn’t much to it. To run this code locate the directory of your project in terminal and type

php index.php

or go to the url in a browser (I’m not going to tell you how to live your life) and you will start to see the glorious data we were looking for.
Screen Shot 2014-02-11 at 11.56.07 PM
PHP simple html dom parser is a pretty cool project, and has lots of features that can really help you scrape the specific data your are looking for. For the complete manual take a look at http://simplehtmldom.sourceforge.net/manual.htm
One thing I would like to also add before you go is to throttle your scrapes. You usually aren’t scraping your own websites, so keep this in mind and slow down you program to a considerate rate.

Thanks for reading and I hope you guys enjoyed this basic example. Hopefully it will lead you to scraping glory!

Active navigation link with javascript / jQuery

Navigation is something that almost every web app has to deal with, and most of the time navigation will have an active state. There are a couple of ways to do this, and I am going to demonstrate using  jQuery as well as plain javascript just in case you don’t have jQuery in your project.

Bootstrap Navigation

So lets take a look at a normal bootstrap navigation


Setting active navigation

What we want to do is get the current url, and then loop through each menu item and check to see if the href is equal to the url. We also want to check if the if the menu item is part of a dropdown menu, if it we want to find the parent menu item and set it to active as well. Here is what the javascript looks like.

$().ready(function(){
  setActiveLink();
});


function setActiveLink(){

  // get the current url
  var url = window.location.pathname;
  // decode the url
  url = decodeURIComponent(url);

  // this is incase your project isn't in the root directory of your url
  // for example localhost/ActiveNavLink/index.html
  projectPrefix = "/ActiveNavLink/";

  // loop through each nav li
  $('.nav li').each(function(){

    // get the menu a tag and get its href attribute
    var href = $(this).find('a').attr('href');

    // href can be undinded if there is a divider
    if(href === undefined)
      return;

    // add the project prefix
    href =  projectPrefix + href;
    
    // check if the menu item is equal to the current url    
    if(url.substring(0, href.length) == href){
      // set active class to li
      $(this).addClass('active');

      // check if there is a parent dropdown
      var parentDropDown = $(this).closest('.dropdown');
      // if there is a parent dropdown set it to active as well
      if(parentDropDown !== undefined){
        parentDropDown.addClass('active');
      }
    }
      
  });

}

Screen Shot 2014-02-11 at 2.49.55 PM
If you want to take a look at a working demo take a look at https://github.com/barrettbreshears/ActiveNavLink. You will probably need to change minor details to make this work in your project, but its pretty straight forward. Hope this is helpful!

Stay focused and get stuff done

Programming with babyA little over two months ago my wife and I had our first child. I has been an amazing experience, and has changed my life forever. The biggest thing that has changed for me is I don’t have any time or energy anymore! I used to be able to work all day, hang out with the wife, get back to programming, get to bed about 2 am and wake up at 7 or 8 am and do the whole thing all over. Now it seems like 8 pm hits and I am ready for SLEEP. This lack of time and energy has actually been a huge eye opener for me, and I feel like I am more focused, and actually getting more done in less time. I wanted to share my simple strategies for staying on task, and hopefully they can help you out.

Write out your tasks

It doesn’t matter if you are planning on working 1/2 hr or 12 hrs, write out what you need to accomplished. I work in an agile dev environment so I’m used to having my user stories/ tasks laid out, but I never planned out my day in this way. It is extremely helpful and having a  plan helps me stay focused. It also makes me feel like I’m getting stuff done when I can cross stuff on my task off.

Try to remove distractions

I work from home, and when I’m in my office and the door is closed its like I’m not in the house. There are obvious exceptions, like if the baby became a poop/vomit fountain and my wife needs assistance or the house is on fire, but if its something small it can wait until work is done.

Reddit (Your internet weakness)

I have a serious reddit addiction, and its crazy how fast minutes can turn into hours and hours into days browsing reddit. It’s not just reddit though, working as a web developer and being online all day can be challenging  especially if you are self employed, work from home, or don’t have a boss that is able to see your screen. There is a great chrome extension called stay focused that can block sites and is really configurable.

Don’t forget to take some time off

One of the worst things that can happen to your productivity and overall mental well being is getting brunt out. This is one of the most challenging things for me to do. I am always thinking about work, and wanting to get a little extra work in to help get ahead in a project. I’ve found that when I do take one or two days off I am focused and ready to get work done.

 

Building mobile apps with AngularJS: Ionic Framework powered by Angular

ionic_logo
A couple weeks ago when wondering the web I came across an exciting new HTML 5 mobile framework that is powered by angular, and looks pretty cool! Its called the Ionic framework. It’s still in alpha, but it looks very promising, and here are some of the highlights from their website.

  • Fast and responsive
    With minimal DOM manipulation, zero jQuery, and hardware accelerated transitions, one thing is for sure: you’ll be impressed.

  • Powered By AngularJS
    Gives a great MVC architecture to you apps! I’m a huge fan of angular and this really is the reason I’m trying out this framework.

  • Built with SASS
    Easily style you app with sass!

  • Documentation / Guide
    Has complete documentation  and guide that will help you get up to speed quickly.

  • Yeoman Generator for Ionic
    Yeoman is a great scaffolding tool to make your app development even quicker! https://github.com/diegonetto/generator-ionic

I haven’t been able to get into a complex app yet, but just playing around with it and creating basic demos I’m very impressed. Definitely check it out if you get a chance.

Sencha Touch | A look back at my first year

sencha-tools-250The last year and a half has allowed me to really focus on front end development, more specifically front end development with html5 for mobile devices. I wanted to share my experiences to hopefully help developers choose the right framework if they are considering using Sencha Touch or building a HTML 5 hybrid app. I started out by choosing between 3 front end mobile frameworks that I had heard a lot about which were: Dojo Mobile, jQuery Mobile and Sencha Touch. I choose Sencha Touch because it seemed like it is the most full featured mobile framework, used a MVC architecture, had good docs, a ton of pre built components to use, and a lot of good demos.

Here’s what I didn’t like:

Fist I should probably disclose that due to project requirements I had to build the app inside of IBM’s Worklight platform, which definitely made development life more difficult, and the app not perform as well. Worklight is IBM’s version of Cordova/Phone Gap that runs a server and provides a method for talking to a backend and returning data to and from your app, sounds like a great idea, but it was terrible and clunky to work with. Anyway back to Sencha.

  • The framework is really big:
    The uncompressed version of the framework is over 90,000  lines of code(2.9 MB). That’s a lot of javascript, and thats a lot of code to be loaded into memory on a mobile device. The compressed version of the framework is 139 kb which isn’t too bad, but its not great. This also lead to some really weird javascript debugging, which lead to hours of tinkering following break points and stepping through this enormous code base.
  • There is a steep learning curve:
    It took a  couple of months working full time in the framework to get really comfortable with it, and have the confidence to be able to say “Ya sure we can do that!” or “I don’t think that would be possible”
  • Performance was always an issue:
    It seemed like everything we did had to be reworked and optimized just to get decent performance, from screen transitions, scrolling on long pages and even getting button or tab taps to be responsive. Again Worklight might have played some role in performance issues but, you could definitely tell you were in a hybrid app. I have seen posts about how Sencha’s performance can be awesome, like the facebook vs fastbook (sencha html5 rebuild). I will be the first to admit that it was probably something that I was doing causing the performance issues, but I would like a framework to be robust enough to have great performance without having to optimize every single line of code, or be required to have the same understanding of the framework as the engineers that built it.
  • iOS 7 release issues
    When iOS 7 was first released there were significant issues with inputs and different ui elements that delayed the release of the app until they were fixed, which took weird css hacks and tinkering in the source code. Here is a great article on the issues that sencha faced http://www.sencha.com/blog/the-html5-scorecard-the-good-the-bad-and-the-ugly-in-ios7. This to me is a pretty big issue. I want the apps that I build and spend years of my life working on to work, and work great.

Here is what I liked:

  • Theming
    Sencha’s themes are built with compass, and make it super easy to theme and customize your apps. If you have any background with sass, compass or less you will have no problem in styling you apps. The docs have great guides on getting started with theming, and when you want to style specific components the docs display available mixins and variables that you will need to use http://docs.sencha.com/touch/2.3.1/#!/api/Ext.tab.Bar-css_mixin-sencha-tabbar-ui. This also comes with a down side I guess, if you don’t want to use compass, then sencha is definitely not for you, trying to theme an app without compass would be a huge pain. There are also default themes for a number of different operating systems (iOS, Android, Windows Phone) which can get you started quickly.
  • Docs
    The documentation is really thorough and very helpful. They have guides on getting started, tutorials, and demo apps. You end up relying on the docs for a lot for everything from what events are available to a component, styling, and component properties and methods.
  • Components
    There is a lot of functionality already built out for you, you can take a look at all the different components available in Sencha’s Kitchen sink app. This made it easy to quickly build a html 5 app that had the look and feel of a native app. Once you got over the learning curve components make a lot of sense and are pretty easy to use and create your own.
  • Architecture
    I like the MVC approach to building apps. It made it easy for our team to work together and we didn’t have to worry about structuring out app.
  • Cross Platform
    This was the reason for building a hybrid app in the first place, it allowed us to use a single code base and deploy to multiple markets. It also cuts down in development time.

Overall thoughts

Overall I think Sencha definitely has its uses and has some great ideas on HTML 5 app development but if I had to do it all over again I  would not use Sencha. For a cross platform hybrid app I would lean more towards an Angular, Ember or Backbone because you have more freedom to tweak  you app to exactly how you want it. I just don’t have the confidence that building the app with Sencha will preform well enough or will break if an OS update comes out. I understand when building a hybrid app you can’t expect 100% native app performance, but you when it effects your user’s experience all the benefits of using the framework really don’t count for anything. Hope this helps, let me know if you have any questions!

Create angularJS filter!

Lately I have been playing with AngularJS and I am in love with it. Angular has these really cool components called filters which are described as:

[custom_blockquote style=” grey”] A filter formats the value of an expression for display to the user. They can be used in view templates, controllers or services and it is easy to define your own filter. [/custom_blockquote]

hodorLets Get Started

So game of thrones season 4 will be here in a couple of months so I thought we should build a Hodor filter to honor the great and noble Hodor. 

Our filter will take a string and translate it into Hodor.

Since this is just a demo, we are going to set up a super simple app that has a controller which looks like this:


	
		My Custom Filter
		
		
	
	

		

{{pageHeading | hodor}}

As you can see this is a pretty simple angular app with a single controller that sets our page heading data. We display our pageHeading property and add our hodor filter. We also attach our pageHeading model to the textarea so we can see the filter in action!

Now lets move on to the filter. We are going to want to use this in all our projects so we need create a new module just for our filter, and call the filter service.

angular.module('hodor-filter', []).filter('hodor', function(){

	return function(input){
		var hodor = [
			'H',
			'o',
			'd',
			'o',
			'r',
			' '
		];

		var stringPos = 0;
		var hodorString = "";
		for (var i = 0; i <input.length; i++) {
			var chr = hodor[i%6];
			hodorString = hodorString + chr;
		}

		return hodorString;

	};

});
  • Lets take a look at whats going on here:
  • – Declare our hodor-filter module and hodor filter
  • – Return a function that gets passed an input parameter
  • – Set up a Hodor array we will use this to replace characters in the input string
  • – Loop through all the characters and replace them with the correlating Hodor character
  • – Return the new hodorString

And thats it! Creating a filter is that easy! If you would like to download the project it is available on GitHub Hodor-Angular-Filter

Build a custom UICollectionViewCell

Today I was working on an iPhone project that required a custom UICollectionViewCell in my UICollectionView. Utilizing interface builder, and a custom xib you use this same technique to customize just about any UI component.

I made my the project available from git hub:

https://github.com/barrettbreshears/CustomCollectionViewCell

Add new view

Open up your project and add a new user interface view file. I am going to name mine MyCustomCell.xib. Open your new file and you will see an empty view. Select the view and delete it, we will be replacing it with a CollectionViewCell. Now drag a UICollectionViewCell onto the xib file. You should get something that looks like this:
Custom Collection Veiw Cell

For this demo we are just going to add a label, that we can set a custom message in each cell. To add a label to our cell drag a label from the object library onto the cell.

Cell with label

With our view set up lets get to our custom cell’s class file. Create a new Cocoa Touch object c class. And give it the same name as your custom xib, and select UICollectionViewCell as the subclass.

Add cocoa touch fileMyCustomCell

 

Once the file is created we will add our our label as an IBOutlet. This is what   MyCustomCell.h looks like now

//
//  MyCustomCell.h
//  CustomCollectionCell
//
//  Created by Barrett Breshears on 11/14/13.
//  Copyright (c) 2013 Barrett Breshears. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface MyCustomCell : UICollectionViewCell
@property (nonatomic, strong) IBOutlet UILabel *customLabel;
@end

Go back to your custom view cell and select the CollectionViewCell and select the identity inspector. Under the custom class property set MyCustom cell as the Class. This will give you access to the IBOutlets specified in MyCustomCell.h. After the custom class is set select the connections inspector to view your available connects. Under Outlets customLabel should appear. Drag and drop customLabel onto the label inside the collection cell.

Set custom class

Connect customLabel Outlet

 

Now the hard part is over! Lets hook up our custom cell, by registering the nib with the collection view. My demo app is a single view with a collection as a subview. Below is my view controller.

#import "CCCViewController.h"
#import "MyCustomCell.h"

@interface CCCViewController ()

@end

@implementation CCCViewController

-(void)viewWillAppear:(BOOL)animated{
    [self.myCollection registerNib:[UINib nibWithNibName:@"MyCustomCell" bundle:[NSBundle mainBundle]]
        forCellWithReuseIdentifier:@"MyCustomCell"];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 10;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MyCustomCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCustomCell" forIndexPath:indexPath];
    [cell.customLabel setText:[NSString stringWithFormat:@"My custom cell %ld", (long)indexPath.row]];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(150, 150);
}

@end

When we run the app we get the our custom collection view cell loaded.

Screen Shot 2013-11-14 at 1.40.42 AM

Getting started with sencha touch!

senchatouch

Sencha Touch is a HTML 5 framework that allows you to create cross platform mobile apps. When used with cordova you can build HTML apps that look and feel like a native app allowing you to cut down in your development time and budget. The frameworks learning curve is a little steep but once you get it down, development is quick and painless.

Lets get started

To get started we are going to need to download a couple things and get our environment set up. It might seem like a lot, but once you are set up you should be able to create Touch projects quick and easy. Here is what we need to download:

Now that we have everything downloaded, install MAMP to get your server up and running, and install sencha cmd. Once sencha cmd is installed run the following cmd:

sencha

You should see something like this in your terminal:
Terminal output

This means sencha cmd is installed correctly and you we are getting close to creating our app.

Next take your sencha touch sdk download  and unzip its contents into you web server directory, put mine under a touch directory. This will allow you view documentation and demo apps locally on your machine, as well as a good getting started guide http://localhost/touch/SETUP.html.

Now that everything is set up lets build our app! We will be using sencha cmd to scaffold out the app. The command we are going to use is:

sencha -sdk /path/to/sencha-touch-sdk generate app MyApp /path/to/www/myapp

With my setup this is what my command will look like for my app called PowPowPowerball

sencha -sdk /Applications/MAMP/htdocs/touch generate app PowPowPowerball /Applications/MAMP/htdocs/PowPowPowerball

And thats it, your app is created. With your web server running navigate to your project. It should look like this:
Your new sencha touch app

Take a look inside your project and you will see what sencha cmd has built out. Below is the basic layout of the project.

.sencha/                # Sencha-specific files (for example configuration)
    app/                # Application-specific content
        sencha.cfg      # Configuration file for Sencha Cmd
        plugin.xml      # Plugin for Sencha Cmd
    workspace/          # Workspace-specific content (see below)
        sencha.cfg      # Configuration file for Sencha Cmd
        plugin.xml      # Plugin for Sencha Cmd

touch/                  # A copy of the Sencha Touch SDK
    cmd/                # Sencha Touch-specific content for Sencha Cmd
        sencha.cfg      # Configuration file for Sencha Cmd
        plugin.xml      # Plugin for Sencha Cmd
    src/                # The Sench Touch source
    sencha-touch-*.js   # Pre-compiled and bootstrap files
    ...

app                     # Your application's source code in MVC structure
    controller
    model
    profile
    store
    view
        Main.js         # The main view of the application

resources
    css
        app.css         # The main stylesheet, compiled from app.scss

    sass
        app.scss        # The Sass file which compiles to app.css above,
                        # includes Sencha Touch theme by default

    icons               # Application icons for all mobile devices
                        # When replacing these default images with your own,
                        # make sure the file name and the dimension stays exactly the same
        ...
    loading             # Application start-up screens for iOS devices
                        # Similarly to icons, make sure the file names and
                        # dimension stays the same
        ...
    images              # Put other images used by your application here

index.html
app.js                  # Contains application's initialization logic
app.json                # Application descriptor
packager.json           # Configuration for native packaging

Thats it, now get started building out your app!