ES6 Features

I have been using ES6/ES2015 for a few months in my full time job. Its been a gradual adoption process taking on the new features as and when we see fit. Over these months I have built up a list of my new goto patterns for JavaScript taking advantage of ES6.

Const & Let

Let

One of the biggest changes with ES6 is the addition of const and let. Let provides a means to define variables inside block scope. This can help to combat the existing hoisting problems with JavaScript.

// ES5
if (foo === 'foo')
   console.log(bar);
   var bar = 'bar'
   console.log(bar);
}

In the above example var will be hoisted and could potentially cause issues with the code.

// ES6
if (foo === 'foo')
   console.log(bar);
   let bar = 'bar'
   console.log(bar);
}

In the let example the variable will still be hoisted however the referencing of the variable will be done in the block before hand. This means that when running the ES5 code you will just see an undefined message for the first console. However in the let case you will get a reference error indicating that you have tried to use a var before it has been declared.

Const

Const provides a way to create a constant that is either global or local scoped. When defining a constant you must provide a value as the value cannot be changed later.

// define MY_CONST as a constant and give it the value 7
const MY_CONST = 7;
// this will fail silently
MY_CONST = 20;
// will print 7
console.log("my CONST is: " + MY_CONST);
// trying to redeclare a constant throws an error 
const MY_CONST = 20;
// the name MY_CONST is reserved for constant above, so this will also fail
var MY_CONST = 20; 
// MY_CONST is still 7
console.log("my CONST is " + MY_CONST);

There is some controversy around const as it’s not what some people might expect for example the code below will not throw an error:

const MY_CONST = {foo: 'bar'}
MY_CONST.foo = 'test'
console.log(MY_CONST) // Object {foo: "test"}

An alterative to const would be to use Object.freeze()

Arrow Functions

Arrow function provide a cleaner syntax for the standard function expression and it also binds the lexical this scope to the function. This not only makes the code look clean but also takes away the pain of scope binding. No more var that = this also all arrow functions are anonymous. You can use arrow functions in a number of ways:

 //ES6
(param) => { statements }
(param) => expression
param => { statements }
// A function with no parameters requires parentheses or an underscore:
() => { statements }
_ => { statements }

Spread

The spread operator provides a cleaner way of dealing with arguments or params for function. This becomes very useful when working with React and JSX as the below example shows:

var params = {foo: 'bar', bar: 'foo'};
//Without spread
<MyElement foo={params.foo} bar={params.bar} />

//With spread
<MyElement {...params}/>

In both examples the JSX element is getting the foo and bar params, the second is cleaner and also reduced the maintenance of the code. As the params object grows you do not need to update the JSX element declaration.

Parameter Destructuring

Parameter destruction is one of the gems I have found recently. It allows you to clean up the code when you know what you need from a param. An example of this would be a using a promise/async or callback function that returns you a result. In a lot of cases you only need one part of the response. You can now define what you want and ignore the rest.

//Without param destructuring
myfunction((err, result) => {
    if (!err) {
        console.log(result.body);
    }
});

//With param destructuring
myfunction((err, {body}) => {
    if (!err) {
        console.log(body);
    }
});

One gotcha I have found with this is when the code is transplied, when Babel transpliles the code it looks like this:

//Transplied
myfunction((err, _ref) => {
    var body = _ref.body;
    if (!err) {
        console.log(body);
    }
});

If the result param is undefined or null this will fail at run time, causing an unexpected error. This has caught me out before when the expected result was not defined and only failed while in production.

Object Literals

Last but not least Object literals. This is another clean syntax which I have been using alot. It provides a shortcut to defining variables.

var foo = 'bar';
var test = { foo };
console.log(test.foo); // 'bar';

This can also work when exporting modules, we have all seen the code below before:

function plus() {
    ....
}

function subtract() {
    ...
}

function total() {
    ....
}

module.exports = {
    plus: plus,
    subtract: subtract,
    total: total
};

This follows the revealing module pattern and is okay but we could use object literals to clean this up.

module.exports = { plus, subtract, total };

It’s a small change but reduces bulk and provides a clean and simple syntax to read.

That’s all for now

This is just a few examples of what I have been using but I’m still building up my list of ES6 features and hoping to get into some ES7 features soon. If you know of any other great features drop a comment.

facebooktwittergoogle_plusredditpinterestlinkedinmail
 

Should You Commit Compiled Code?

Working on a Java project you would never dream of committing a built war or jar file, so when working with JavaScript why would you think of committing the compiled source. So many projects I have worked on have by default commit the dist/lib code. This adds bloat and unnecessary steps to committing and merging such as making sure that you build before committing files and that you build when merging.

Preventing Commits of Complied Code

When setting up a new project always create a .gitignore file and add this to the project. For most projects I have worked on we have always used a dist/lib folder for the compiled source. For these cases add the following to your .gitignore.

# compiled source
dist
lib

if you have already committed the dist or lib you can stop tracking the files by using the following git command: git rm -r –cached

How to Provide Users with the Compiled Source

The easiest and most recommended (personal opinion) method for distributing your source is via npm. Npm allows you to publish code to a central repository and allow users to quickly access and use the code. The reason that I prefer Npm over other package managers like bower is due to the Npm repository, the repository allows publishers to push only the needed content so that users only pull down and have access that what they need. Bower however acts more like a link to git repositories which in turn requires publishers to commit complied source.

NPM Publish

To publish to Npm you can follow some simple steps that will have you pushing code in no time.
Create your npm account. You can also pay to have private repositories and push/get from these.
– Add the name field to the package.json file in your project.
– Add a prepublish task to the npm scripts
– Run npm publish

You can see an example file below:

{
  "name": "module-name",
  "version": "10.3.1",
  "description": "An example module to illustrate the usage of a package.json",
  "author": "Your Name ",
  "scripts": {
    "test": "echo 'No Tests'",
    "start": "node index.js",
    "prepublish": "uglifyjs --compress --mangle input.js"
  },
  "main": "dist/foo.js",
......

You can either have a build task that you call from the prepublish or just call the build commands. Now when you run npm publish the prepublish will run and compile your source. Now you need to make sure that only this gets pushed to the Npm repository. This can be achieved by using a .npmignore similar to the .gitinore however this will list all your project content except for the dist/lib folders.

Now your project is setup to only publish and track what users need and want.

facebooktwittergoogle_plusredditpinterestlinkedinmail
 

SMACSS: Scalable and Modular Architecture for CSS

I have been working a lot recently with CSS and updating application styles.

I have always followed the simple pattern of placing all CSS in one file (stlye.css). However when I started started working with SASS I started to break up the styles into logical files, each file folding the styles for a page or a section of a page. This still ended led to issues are the file would grow and I would usually end up with reproduced styles and when it came to removing a style it was hard to trace.

SMACSS

SMACSS is a style guide you can follow that will provide more organisation for your css. Its promoted as not a framework but a way to examine your design process. SMACSS is broken up into a number of categories:
– Base
– Layout
– Module
– State
– Theme

Each of these categories can be used to structure the css of a project.

Base

Base styles are styles that will cover the whole project. Root document styles such as the body text, links styles and anything else that can cover the whole project.

body {
    margin: 0;
    padding: 0;
    font-family: "Bell MT", BellMT, Garamond, Georgia, “Times New Roman”, Times, serif;
    line-height: 1.5;
    color: #333;
}
a {
  color: #039;
}

We can see from the example above that we are setting the font for the document and also setting the links colours. Anything that is not specific to a part of the application can be added to your base.

Layout

Layout as you can guess takes responsibility for the layout of the document. The layout would contain the styles for blocks on the page such as a nav bar, header, main content area and a footer. The layout file could look something like:

nav {
  width: 20%;
  float: left;
},
main {
  width: 80%
  float: left;
}
footer {
  width: 100%
}

Here we can see the different sections of the application.

Modules

Modules are used to store the different parts of the application, If you page has blog posts on it and each post has a preview. This is a module you can contain the styles for that module in a file named preview.css. You can also extend modules and have submodules.

State

State rules are ways to describe a our module or layout will look when in a particular state. Is it hidden or expanded? Is it active or inactive? They are about describing how a module or layout looks on screens that are smaller or bigger. They are also about describing how a module might look in different views like the home page or the inside page.

Theme

Themes are similar to state in that the can describe how a part of the page looks. However different to state the theme can be used to change to look of the page based on a user preference.

Why SMACSS

So you know what SMACSS can do for your css but why should you use it. When working on large scale JavaScript applications it is common to break up the code into manageable areas such as modules or use a MVC style structure. Why not apply the same to css, when multiple developers are working on code things can get messy. Merge conflicts, code duplication and complexity can and will happen unless some rules are introduced. With SMACSS you can break down the css into manageable chunks and allow for developers to work together with little to no issues.

To learn more about CSS architecture, layout and best practices in writing and managing CSS layouts, check out the CSS Layout Tutorial from Toptal.

facebooktwittergoogle_plusredditpinterestlinkedinmail
 

CSS Flexbox

Flexbox is a CSS property that aims to provide a better method to page layout that the currently popular methods using floats. I recently came across Flexbox when working on CSS bug. I preformed the usual Stackoverflow search and blindly copied and pasted the answer into my code. As expected everything work, but why? What was tis Flexbox I was seeing?

I decided to look into Flexbox and here is a very basic overview of how to use Flexbox. Flexbox is an alternative was to control page layout, without the need for floats. Floats have there own advantages and disadvantages. The main idea behind Flexbox is the ability for the container element to dynamically alter the size of its child elements. This leans it use towards responsive design as it will work to fill the container area as best as possible.

The example below shows a container div with 5 children, the container has flex as is display while the children all have flex:1 set.

See the Pen ojXvBd by Chris Laughlin (@chrislaughlin) on CodePen.

Note that each child is of equal height and width and all work to fill the parent container. This is the power of Flexbox, there is no need to set any width or height of the container or the children. Also note that the flex:1 of the child is does not effect the layout. This will be applied to each child and will be come more clear in the next example.

See the Pen pjJzzv by Chris Laughlin (@chrislaughlin) on CodePen.

You can see from the above example box 2 is bigger this is because we have set it with a higher flex than the others. So now box 2 is two times the size than the others. This can be done for any of the boxes just by changing the flex value. So on that thought you could potentially make a 3 column layout (that was all the rage back in the day) by setting the flex of the middle column and you get responsive design for free.

See the Pen zvGOYN by Chris Laughlin (@chrislaughlin) on CodePen.

Browser Support

Now for the bad part, there is currently not full browser support for Flexbox, currently Chrome, Firefox, Safari, IE (11), Opera and Android (4.4.4+) have full support. Other browsers require you to add a prefix however if you are using SASS or LESS you could use a mixin to achieve this.

facebooktwittergoogle_plusredditpinterestlinkedinmail
 

JavaScript Developers Toolkit

 
My tool kit has grown over the years and even more so since I became a focused and dedicated JavaScript developer. From development environments, online resources and third party tools.
 
## IDE
As JavaScript does not require compiling you could write it all in notepad or any basic text editor as the browser will handle the code. But when developing large scale JavaScript applications you need more tools and features from your IDE.

My IDE of choice is WebStrom when I worked on Java based projects I used Intellij and it was a dream to use which made WebStrom the only option for me. The feature set was above par to any other development environment I had used. Features such as intellisense (which is extremely powerful), being able to find method usages and definitions, code quality checking and auto refactoring, source control tools built in like merging, a built in terminal, debugging for not only client side JavaScript, NodeJS and even Grunt and Gulp. I also blogged before about the power of the keybindings in WebStrom/Intellj

However this does come at a cost, there are a number of great free alternatives such as Sublime Text, Atom, Aptana Studio, Komodo Edit to name a few. Each with a different set of features, pros and cons.

Third Party Apps

So you have an IDE but there are other apps out there that can aid the developer. Two I use on a daily bases are SIP colour picker and LICEcap.

SIP

SIP is a powerful colour picker that will work anywhere on the screen and provide colours in a number of different formats to suit any development needs. It also keeps track of the most recent colours you have picked.

LICEcap

LICEcap is a tool for generating gif files from recording your screen, this comes in useful when developing UI components and trying to share these with other developers. When documenting a UI code base I always add a gif of the UI component in action. An alternative to LICEcap is Record It however this tool auto uploads the gif which is not great if you are working with internal products or products that have not been released yet.

Online Tools

Ove the years I have built up a collection of online tools or reference sites that I use on a daily basis’s. Here are some:

JSFiddle

JSFiddle is probably one of the most known online tools for web developers, it allows you to create online projects with just one html, css and JavaScript file, however you can add third party code files. This is a great tool for sharing code examples when either getting help/advice or showing off some new code or feature. There has also recently been a release of a ES6 Fiddle to allow for online editing of ES6 code.

JS Bin

JSBin is almost the same as JSFiddle however has some extra features such as a console panel. The main reason I use JS Bin is when I cant get some code to work in JSFiddle I double check on JSBin to remove any doubts. I have also experienced some issues with JSFiddle and company proxy servers blocking the output of the Fiddle.

Code Pen

Code Pen is probably one of the best looking out of the code playgrounds, It seems to be more focused on the look and feel of code. If you check the examples pages there are some beautiful examples of JavaScript and CSS. The interface is clean and simple also which works well when you want to focus on the code at hand.

JS Perf

JS Perf is a JavaScript performance testing site allowing you to pit different methods of doing the same action against each other and see which one out preforms the other. I use this a lot in work when dealing with different patterns and even different methods from different libs. I have used it before when testing the performance of lodash vs underscore vs jQuery vs ES5.

Reference Tools

Having all the tools are great but not knowing how to develop or how to over come bugs makes all the tools useless.

MDN (Mozillia Developer Network)

MDN is a great site for looking up not only JavaScript but HTML and CSS API documentation the site also provides news and examples. An example of the API documenatation can be found n the Flexbox page, the page provides information on the API, examples and the browser compatibility.

Dev Docs

Dev Docs is a must have tab open in your browser. If you work with JavaScript you most likely work with a few frameworks, you will at some point have to look into the docs for that framework. Dev docs pull in all the JavaScript frameworks that you want and keeps them in one handy tab. With the ablitiy to search and save for offline use it will save you some much time. You can open github issues to get other frameworks added.

Keeping up with the Joneses

If you are into JavaScript you most likely have realised that the world of JavaScript moves fast and you need to find ways to keep up. Here are some methods and resources I use:

Podcasts

JavaScript Jabber

JavaScript Jabber is a weekly podcast that discusses font and backend JavaScript, coding best practices, coding environments and the JavaScript community. The podcast has covered a very wide range of topics with regular guest from big name companies and communities from Angular and ember core developers to Brendan Eich (which was my favourite show to date).

NodeUp

In very simple terms NodeUp is a weekly podcast is a about Node.js, each week a different aspect of node is looked at usually with guests who are closely related to the topic and can provide a deep insight into the technology. With big name guests from the likes of Netflix, Socket IO developers and even the people behind NPM.

Shop Talk

Shop Talk is a weekly front end development podcast that has a mix-up of shows with guests from the tech world and shows for answering listener submitted questions.

The Changelog

The Changelog podcast s not just for web development but does contain a lot for the web developer. Each week a core developer of a tool or framework talks about the progression of the project where it has been where its going.

News Feeds / Twitter Accounts

I use Reddit for most of my JavaScript news needs, the following subreddits are vey usefull:

  • /r/angularjs
  • /r/backbonejs
  • /r/css
  • /r/emberjs
  • /r/Frontend
  • /r/HTML
  • /r/javascript
  • /r/marionettejs
  • /r/Meteor
  • /r/mongodb
  • /r/node
  • /r/programmingtools
  • /r/reactjs
  • /r/rubyonrails
  • /r/WatchPeopleCode

Twitter can also be a great resource if you follow the correct accounts:

  • https://twitter.com/paul_irish
  • https://twitter.com/addyosmani
  • https://twitter.com/davidwalshblog
  • https://twitter.com/jashkenas

Books

### JavaScript: The Good Parts
The must read JavaScript book, I first read this when I got into JavaScript development. I still keep a copy on my desk almost 7 years later. This book covers the basics of JavaScript a sets you up to be a great developer.

Learning JavaScript Design Patterns

This is a great book to move onto after the good parts as it takes you though the different design patterns and best practices in JavaScript. The book helps you understand JavaScript in a way that allows you to develop large applications and become better at managing code.

High Performance JavaScript

This is a nice book to keep around for reference on how to make your code as performant as possible. There are some really useful concepts that can help any level of developer.

Conclusion

This has been a detailed look at the JavaScript developers toolkit, every developer knows what works best for them and so some of the tools I mentioned might not be for you. Your toolkit is never complete so new tools will come and go, if you have something that helps you work or find useful in some way drop a comment.

This post has been powered by Genesis – Turn it On Again and Finca Filadelfia

facebooktwittergoogle_plusredditpinterestlinkedinmail
 

Never use Window.event

I had recently fixed bugs in different applications each with the same mistake.
In both instances the developer had used the Window.event object inside a browser
event. Something like below:

buttonClicked: function() {
  if(Window.event.currentTarget) {
    .....
  }
}

The main issue here is we are using the browser created global event object, this is
specific to IE and chrome. So what is bad about that you ask? Firefox does not support
this and your application has now lost all Firefox support. The proper way to handle
the events is to use the event param that is passed to the function by default.

buttonClicked: function(event) {
  if(event.currentTarget) {
    .....
  }
}

This method is supported by all browsers. This method also moves you away from
using the Window object which is a global and out of priceable should be avoided
when possible.

facebooktwittergoogle_plusredditpinterestlinkedinmail
 

UnderscoreJS Compose

After watching a video about UnderscoreJS
I saw the use of the compose function, I have never noticed this when skimming through the underscore docs. The compose function:
> Returns the composition of a list of functions, where each function consumes the return value of the function that follows. In math terms, composing the functions f(), g(), and h() produces f(g(h())).

So to add some context to this; the compose function will take in multiple functions as its params and execute each of these passing the result in to the next function. One thing to note is that the functions are run in reverse order to which they were passed in. Why does this matter? Well if you have used underscore at any length you will have most likely used the chain function to try and clean up the use of multiple underscore functions:

_.chain(people)
	.sortBy(function(person) { return person.age; })
	.map(function(person) { return person.name + " is " + person.age})
	.first()
	.value();
//"mark is 14"

This code is taking an array of people and sorting them by age then returning a string for the person and getting the first string in the array. This works and is “functional” however this could be cleaner. This is where the compose function comes in we can use compose to link the functions together and not only provide cleaner code but also make the code reusable by default.

var people = [{name: "john", age: 21}, {name: "mark", age: 14}, {name: "harry", age: 40}, {name: "Mary", age: 70}];
var mapNameAndAge = function(people) {
    return _.map(people, function(person) {
        return person.name + " is " + person.age;
    });
}
var sortByAge = function(people) {
    return _.sortBy(people, 'age');
}

var comp = _.compose(_.first, mapNameAndAge, sortByAge);
comp(people);
//"mark is 14"

So you can see there is some set up as you need to define the functions before you call compose however the final composed function is much cleaner and clearer to understand. This is also reuseable by defualt. This does not stop at underscore this can be used in other places such as API calls and data calls e.g:

var updateUser = _.compose(save, update, find);
updateUser({id: 1, location: london});
facebooktwittergoogle_plusredditpinterestlinkedinmail
 

BelTech 2015 The internet of Things

The main theme of the discussion was that IoT (Internet of Things) was everywhere. Michael Crossey (Intel) discussed the changes in IoT and how it is related to the dropping cost of tech. This is related to Moore’s lawThe observation made in 1965 by Gordon Moore, co-founder of Intel, that the number of transistors per square inch on integrated circuits had doubled every year since the integrated circuit was invented. Moore predicted that this trend would continue for the foreseeable future.

Progrssion of IoT

Moore’s law can create great value and improve IoT, Intel are using this to build a reference model for vendors to create and expand IoT and help grow their products. John Shaw from Kingspan talk primarily on his own experiences with IoT with his business which provides smart solar solutions. Their solar PV adoption is powered by Intel Quark, Kingspan sees the IoT as a way of connecting not only devices but people, animals and objects in a smart way. John was very quick to brag about the advancements of Kingspan and how their head office is a carbon negative office. IoT helped to achieve this goal by using smart systems that talk to each other and allow the office to work efficiently.

Working with Large Systems

Joe Hughes of Glen Dimplex also focused on how his company was making advancements in the home and commercial cooling/heating by using IoT devices. Using smart heaters customers could control the heating in an energy efficient way. A system built with cloud controlled heating and having direct links to customers systems allows Glen Dimplex to provide an advanced service. Joe also talked about how this could in fact help the national grid. Joe explained that being able to monitor customers on site devices they can monitor energy usages and patterns, which can allow the national grid control the spinning up and down of resources. A question was put to the panel on the security implications of these systems. A product that talks to 1000’s of customer devices and also can talk to the national grid could have the potential to bring down one of the largest connected systems in the country. This is a valid point but as with any product the security must be a high priority.

IoT in Health

Gareth Tolerton of Total Mobile talked about the impact IoT has on health care and how capturing data on patients can help to provide a better health care system. Working with tech like smart locks can provide safe and much needed services to patients that receive at home care. Allowing the programmatic access to care workers. This system addresses issues with people who feel isolated and vulnerable as care workers can be allowed access without having to obtain keys for a patient’s home, if a care worker no longer treats or is linked to a patient then the access can be revoked. Other IoT systems can help to provide personally tailored health care for patients, but as mentioned by Gareth work is still needed to provide trust in the data collected and sufficiently protect the data.

Take Away

One of my main concerns with the growing IoT market space is the maturity of the network and infrastructure currently in place. I recently watched a promotional video for a smart bike pedal that connected via a sim card to the internet and provided the rider with data. I struggle to see the feasibility of devices like this and other IoT devices. I’m currently with a major mobile provider and I struggle to get a full connection when in the centre of Belfast. Bandwidth, connection speeds and coverage are still big issues faced by many people. If we flood the networks with devices fighting for connection we could cripple the already struggling infrastructure.

facebooktwittergoogle_plusredditpinterestlinkedinmail
 

BelTech 2015

I had the pleasure of attending this years BelTech conference hosted in the amazingly designed Titanic building. The conferences was based on a few topics including smart cities, startups and practitioners. I focused on the smart cities and practitioners.

Opening Keynote

The opening keynote was presented by Kate Atkinson the co founder of Datasnap.io a company focused on the development of products that provide data and insight into customer engament. Using proximity tracking technology DataSnap tracks the movement of patrons at venues and provides data to the customer. Kate talked about the challenges of working with customers and trying to improve the data they require. One of the big requests from customers was to have live maps of the location to watch live data of patrons and how the move around a venue. This can be hard to provide when no real detailed floor maps are available. The solution for this was to map the proximity sensors to rooms or areas. Instead of tracking the location of a patron track their movement between sensors. The result gives data on how many patrons move from A to B then to C and how many move from A to C without stopping at B. This allows the customer to workout why patrons are skipping B and find ways to change this.

Smart Cities

The smart cities session was run with a number of mayors from across the UK, US and europe. The discussion started off talking about the state of smart cities currently, the different cities that were brought into question were; Skien (Norway), Lowell (Massachusetts), South Dublin (Ireland) and Donegal (Ireland). The main theme from each mayor was the focus on bringing companies together to provide a better smart city. However this does come with some challenges, the mayor of Donegal talked about issues with the structure of the local government and how parts had been broken up and segregated from other resources such as online payment and the management of customer interactions. This does however provide a gap that can be filled with smart technologies. The mayor of South Dublin made points about how people expect more from the city with the higher taxes being introduced, this is to help provide more services such as free wifi. Whereas the mayor of Lowell focused on how the city was already smart and push more resources into the existing schemes and even starting more projects. These schemes are the usual that people think of when you hear smart city, funding startups and university based incubator programs. A change from the free wifi, online services and tech startups the mayor of Skien focused on how the growth of the smart city can actually benefit the citizens health and lifestyle. One issue facing all cities is the increased life expectancy which in turn puts more pressure on the heath care system. Skien is focused on building smart homes and integrating smart systems into people’s lives to help protect and improve their way of life.

My take away from the talk, smart cities are becoming a big part of the political thought process and are not a thing of the future, some locations are better suited than others. This can be driven on the geographical location such as remote area’s (always hard to provide high speed broadband etc). Some other reasons could be linked to the technical competence of the local government as some of the mayors were not the most conversed in modern tech and this was clear at point of the talk.

You can read more on the talks below:

The Internet of Things

facebooktwittergoogle_plusredditpinterestlinkedinmail
 

Backbone Forms

I was thinking out loud today about Backbone views and how to manage user inputted data. When I has searched for
how to manage forms and handle user data the few examples I saw all used jQuery to pull the values out of the DOM. Which
we all know can cause issues with performance and adds a level of complexity when it comes to maintaining the code, as
the form grows the code used to pull the values out of the text boxes etc will grow.

I was thinking about this for a while until I came up with a pattern that would allow the code to update the model linked
to the view and handle new inputs added to the html without any code changes need in the view or the model. The pattern
(if you could call it that) uses data attributes
on the html to decide if the model needs updating and does this in a dynamic way.

<input type="text" class="listen-to" data-model="input1"/>

The input is decorated with a data-model attribute which will map to an attribute on the model, it also has a “listen-to”
class which will be picked up by the views events.

events: {
            "change .listen-to": "updateModel"
        }

The event will trigger once input has lost focus, this then calls the update model function. The event will fire when any
of the inputs have changed e.g allowing for as many inputs as needed. The event will be passed into the function and this
will be used to find out which attribute of the model to update and what value to update with.

updateModel: function(evt){
            this.model.set(evt.currentTarget.attributes["data-model"].value,
            evt.currentTarget.value);
            //optional: update another view with the latest value in the model
            this.outputView = new OutputView({
                model: this.model,
                el: $("#output_container")
            });

        }

As you can see in the example (hacked together) the evt will hold target that triggered the event. The data-model attribute
is used to get the model attribute to update and the value is taken from the currentTarget. For demo purposes another
is update to show that the changes are made to the model in real time. This could be extended so that a submit button will
call a function that only needs to get the model and do what ever it wants with the values as the model attributes have been
updated as the user has been filling them in.

This takes away the need to use jQuery for getting the values from the inputs and allows more inputs to be added to the
template which out any view code changes.

You can see the full demo here.

facebooktwittergoogle_plusredditpinterestlinkedinmail