Javacript: More functional, less object oriented

A colleague pointed out that when I program in javascript I’m trying to force object oriented programming onto javascript. Rather than keeping with the javascript style of programming. The main problem is I rely on the “new” keyword in my javascript code.

The scenario:

I want a base object, DataInterface, that can handle api methods and data.

I have reusable methods that are interfaced, and then I want to be able to extend “DataInterface” and have the endpoint updated for each instance of the class.

The ideas:

It can be further debated whether this is the right solution for the scenario, but below is the outcome of the discussion:

DataInterface class with methods:

Eg:

1
2
3
4
var DataInterface = function() {
    this.getAll : function() {}; //just an example
    this.getByField : function(field, value) {}; //just an example
}

And this base object has an api endpoint attribute

Eg:

1
2
3
var DataInterface = function() {
    this.endpoint = ‘/endpoint’;
}

Then I want to extend off of this object and have specific data sets,

Eg

1
2
Products.endpoint = ‘one’;
Leads.endpoint = ‘two’;

And then Products and Leads can have additional extended methods, but they inherit the same original behavior from the base class.

The focus:

I am going to focus on just updating the endpoint for two instances of DataInterface, and exclude any methods:

What I originally wrote:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var DataInterface = function() {
    var endpoint;
    this.setEndpoint = function(_endpoint) {
        endpoint = _endpoint;
    };
    this.getEndpoint = function() {
        return endpoint;
    };
    return this;
}

var ProposalService = new DataInterface();
var ProductService = new DataInterface();
ProposalService.setEndpoint('one');
ProductService.setEndpoint('two');

console.log(ProposalService.getEndpoint());
console.log(ProductService.getEndpoint());

What this will output is ‘one’, and then ‘two’ in the console. Two instances of the DataInterface has been created with two unique endpoints.

Out with the new

However, if you remove the “new” keyword, which would make it more “javascript-like”:

Using the same class, but removing “new”.

1
2
3
4
5
6
var ProposalService = DataInterface();
var ProductService = DataInterface();
ProposalService.setEndpoint('one');
ProductService.setEndpoint('two');
console.log(ProposalService.getEndpoint());
console.log(ProductService.getEndpoint());

What will happen now is the console will print out ‘two’, ‘two’. Instead of two instances, we have the same instance being pointed to by 2 variables. So the endpoint is not unique.

In comes the factory pattern

So if we rewrite the code a bit, and have DataInterface as a factory pattern that returns an object, then we can achieve the same result but without the new keyword.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var DataInterface = function() {
    return {
        endpoint : '',
        setEndpoint : function(_endpoint) {
            this.endpoint = _endpoint;
        },
        getEndpoint : function() {
            return this.endpoint;
        }
    };
};

var ProposalService = DataInterface();
var ProductService = DataInterface();
ProposalService.setEndpoint('one');
ProductService.setEndpoint('two');
console.log(ProposalService.getEndpoint());
console.log(ProductService.getEndpoint());

You will now get the output of ‘one’ and ‘two’ in the console, and we did not rely on the “new” keyword.

Just a handy little snippet of code to remember how to not use “new” in javascript when creating instances.

Scaffolding notes on django

Setup notes

Make sure the following is installed:

  • python
  • pip
  • virtualenv

Create a virtual environment:

1
eg: virtualenv env

Make sure django is installed:

1
pip install django

Scaffolding notes:

Create a project:

1
python-admin startproject [projectname]

Optionally create an app

1
2
3
cd [projectname]

python-admin startapp [appname]

Note! Make sure you cd into the project folder so that your app is in the same folder level as manage.py

Also remember to:

Add [appname] to INSTALLED_APPS in settings.py

Create a temp directory with ansible on your local computer

I have a linux environment set up, and I have ansible installed. To see how to setup ansible from scratch follow this blog entry:

Setting up ubuntu linux for ansible development

Some tips that helped me while I was researching ansible

(I’m still learning so this may or may not be right, use it more as stepping stones to progress your own knowledge)

Yml

Ansible makes use of .yml files. Pronounced “yeah-mil”. These files are indent sensitive and you seperate commands be new lines and indents. If you are unfamiliar with yml structures I suggest googling a bit for more information on yml files are structured.

Hosts

There is a global ansible hosts file.

/etc/ansible/hosts

However I always recommend against editing global files. Setup a local inventory file rather.

In your hosts files you declare host level variables that indicate the addresses/locations you would like to access and alter from.

Playbooks

A playbook defines individual plays to be executed in a predefined order

Play

A play is a single task or action to be execute

Modules

A play can use modules to achieve tasks or actions

Lets get started with a simple ansible script to create a directory

Go to a new directory where you would like to create the ansible script and create a folder called “practice”.

In this folder create a yml file called “test.yml”.

Note you can name the yml file anything you like, I’ve just chosen test for this example.

Then create an inventory folder for you hosts file. In the inventory folder add a “hosts” file (no extension).

1
2
3
4
practice/
    inventory/
        hosts
    test.yml

Add hosts

In your “hosts” file add the following:

1
2
[local]
localhost ansible_connection=local

This indicates a variable “local” with the value localhost ansible_connection=local. This tells ansible that you are working on your local machine.

Point to local in test.yml

Add these lines to your test.yml file in order to run your first ansible command.

1
2
- hosts:
  - local

You can check that ansible picks up this configuration by running:

1
<p class="p1">ansible-playbook -i inventory/hosts test.yml --list-hosts</p>

And you should get the response:

1
2
hosts (1):
    localhost

The -i refers to:

-i INVENTORY, –inventory-file=INVENTORY
specify inventory host path
(default=/etc/ansible/hosts) or comma separated host
list.

Then the inventory/hosts indicates the “hosts” file you created in the inventory directory.

The all indicates that all the listed hosts will be displayed. You could also say:

1
ansible-playbook -i inventory/hosts --limit localhost test.yml --list-hosts

And that would filter to just the “local” section. In this case it would return the same result:

1
2
hosts (1):
    localhost

The playbook

Lets start adding a task. Open your test.yml file in you practice folder, and add the following lines:

1
2
[local]
localhost ansible_connection=local

This indicates the environment you wish to alter. Run the playbook:

1
ansible-playbook test.yml -i inventory/hosts

If you get this message:

skipping: no hosts matched

Just make sure you indicated the “-i inventory/hosts” part.

Add tasks

Now we will begin adding the task of creating a new folder. We will be making use of an ansible module called “file”.

Add the following code to your test.yml file:

1
2
3
4
   
  tasks:
    - name: create a dir called temp
      file: path=temp state=directory mode=0755

“name” is referring to the name of the task, this will display in the response on the command line

“file” is the module you are using, and then path, state and mode are configuration values you set for the task

You should now have in your test.yml file:

1
2
3
4
5
- hosts:
  - local
  tasks:
    - name: create a dir called temp
      file: path=temp state=directory mode=0755

Run your ansible playbook

1
ansible-playbook test.yml -i inventory/hosts

You should now see a temp folder inside your practice folder you created.

And that’s it. As simple as that.

Experiment with more file modules

http://docs.ansible.com/ansible/list_of_files_modules.html

Creating angularjs directives in fiddle

A great way to test an angular directive concept out outside of a project is to set up a sandbox version in jsfiddle.

Go to jsfiddle.net

Laying down the foundation for angular js code in fiddle

HTML

In the html block add:

1
<div ng-app="myApp"></div>

fiddleHtml

Note: ng-app=”…” can be any value you choose, I just chose “myApp”

Javascript

Then in the javascript block add:

1
angular.module('myApp', []);

fiddleJS

Your module is the name you chose to use as your app name, I chose “myApp”.

Also make sure your javascript settings are set. I set mine to the following:

Language
Javascript

Frameworks & Extensions
Angular JS 1.4.8

Load Type
No wrap – in <head>

fiddleJSSettings

Use console to track errors

Open your console. To do this on a windows pc you press F12, and a console tab opens at the bottom (or side) of the screen. Make sure you are viewing the “console” tab.

Keep your eye on the console tab for any errors. At this point you should not see any errors, if you do, go through the steps above again. You want to proceed with no errors so it makes it easier for you to debug your directive.

Tip: You can also use console.log like normal to track manual logs while you are coding.

Click the “run” button to the top of your screen and check that no errors occur in the console tab.

fiddleRun

Setting up your directive

Add the directives namespace at the top of the javascript code and add the namespace to the app declaration:

1
2
3
angular.module('directives', []);

angular.module('myApp', [<strong>'directives'</strong>]);

You should run your code, check no errors occur and proceed.

Let’s set up a simple display directive with just a sentence to be displayed.

Simple angular js directive with a tempalte

You can create directives with html internally in the js script.

In the javascript block add the following

1
2
3
4
5
6
angular.module('directives', []).directive('display', function(){
    return {
        template: 'This is just a display'
    }
});
angular.module('myApp', ['directives']);

 

In the html block add the following:

You can run the project now and in the bottom right you should see the sentence “This is just a display”.

fiddleDisplay

 

Done

That’s it. Now you can expand on your directive, look at some examples on the angular js documentation and try out more advanced directives. Add controller, link functions and template urls.

Here is the fiddle link if you would like to see it in action:

https://jsfiddle.net/cari_za/7115oy9z/1/