The Javascript Libraries/packages worth you spend time to know (part 1)

Recently I searched for the most popular programming languages, and I am surprised seeing that JavaScript is still the #1 languages in the list. Although I am a .NET developer, but I have been using JavaScript for many years. My original thought was that only OOP languages like c, c++,Java, c#, etc are called “Programming language”, because all these languages are high-leve, strongly typed, object-oriented, they share a strong, well-defined libraries out-of-box can be used, and they all run on server-side and can be used against multiple-purpose, they are called “advanced programming language”.  the languages like JavaScript is only “low level” language, it is weakly typed, doesn’t have rich built-in libraries, and its main purpose is manipulate HTML, which is used by none “Programmer”. However things seems changed completely since the introduction of Node.js. Since I learnt node.js few years ago, these original “thought” changed me completely.

What makes the JavaScript so powerful in recent years? the answer is Libraries. because JavaScript is open-source, tons of libraries, engines based on JavaScript were built in an amazing speed. Just because the simplicity, weakly typed, prototype-based of the JavaScript, the Libraries build on top of it can be really powerful. Here is a list of JavaScript Libraries: List of JavaScript libraries, on top of these libraries, there are lots of JavaScript packages can help you to achieve more quickly and easily. These packages pack some reusable commonly used functionality together and provide an easy-to-use interface and document for any JavaScript programmer in the open source community.

Here are the most popular JavaScript Libraries/Framework (2017-2018) worth you spend time to know it.

1. ReactJS and React Native

ReactJS is obviously the most popular and fastest grown library. It was originally developed by Facebook, and published to open source in 2013. It is used for building user interfaces specifically for single page applications. The benefit of React is it can be used to create large web applications which can change data, without reloading the page. It is fast, scalable, and simple. It works only on user interfaces in application, so it can be worked with a combination of other JavaScript Libraries, such as AngularJS, Node.js, or ASP.NET MVC.

React Native library were announced in 2015, which provides the react architecture to native mobile applications for iOS and Andriod. It enable user with JavaScript background can build mobile application for iOS and Andriod with one shared code base, but build native iOS and Andriod application. More important, according some analysis and comparisons, the performance of React Native apps are as good as the apps build by using C++/Swift in iOS and Java in Andriod. It is a great choice for cross-mobile-platform, high performance, limited-budget apps.

2. Angular JS

Compare with ReactJS, angular has been around for many years, angular is a much fuller featured framework compared with react. the set up code for angular is a little verbose. even through i was a big fan of Angular, I have almost completely abandon it since I started to use React, since React can do pretty much anything Angular can do, and having the advantage of performance, easy to use, quick to setup, easy to implement, and big time saver. Here I am not going to spend time on Angular, from my opinion the only reason you will adopt Angular over React is because you already well-educated in Angular and don’t have big learning curve, and is well deep-dived in the angular community.

3. Meteor

Meteor is a cross-platform, open source JavaScript library wirtten using node.js. it allows for rapid prototyping and produces cross-platform code (android, iOs, Web). It integrated with MongoDB and uses the Distributed Data Protocol and Publish-subscribe pattern to automatically propagate data changes to clients without requiring the developer to write any synchronization code.

4. Knockout

Knockout is the first JavaScript framework I learnt to build dynamic data two-way data binding web pages. It was so powerful and easy to learn that it quickly earn a large number of developers. It is implemented in the Model-View-ViewModel pattern, so it clearly separate Damian data, view component, and data to be displayed.

Compared with angularjs and react, knockout is like a lightweight angularjs. It doesn’t have lots of features like routing, etc, but it can be achieved by using third party libraries. From the performance perspective, knockout is the slowest From this speed comparison between angular, react, and knockout . It may not necessary to learn knockout at this time since we have much better options, but it is still a very good lightweight library, especially good for the web site only need a dynamic loading pages for existing sites, or built on top of asp.net mvc with only a few pages need asynchronous data loading.

5. Vue.js

Vue is another framework has been gaining rapid progress in the recent years. It adopt the advantage of both react and angular, providing similar roles as the react – playing the V in MVC model. It need to work with other libraries together as a Full-stack JavaScript framework. Because it works in the “view layer” only, it makes it can be easily integrated into other projects/libraries.

Compared with AngularJs, Vue is one-way data binding, and AngularJs is two-way data binding. One-way binding give the developer more controls on how the DOM object is updated, which in turn will increase the performance.

Up coming next

In the next part, I will talk about the JavaScript packages which are very helpful to avoid you to re-invent the wheel.

Advertisements

The Top 10 Mistakes That KnockoutJS Developers Make

1 Modules

Unlike other UI frameworks, Knockout does not come with a built in way to modularize your application. It’s possible to write an entire Knockout app in a single HTML file:

kojs_full

While this runs, it definitely won’t scale to applications of any significant complexity. The official Knockout docs suggest using RequireJS for Asynchronous Module Definition (AMD), and I wholeheartedly second this recommendation. Using RequireJS and the domReady module, the above code refactors into three separate files.

Good.html:

goodhtml

main.js

mainjs

viewModel.js

viewmodeljs

2 var self = this;

Keeping track of this in Knockout can be tough. Setting var self = this; at the top of every view model makes it easy.

For example, if var self = this; is not set then this must be passed into every computed observable:

viewmodeobj

Forgetting to pass in this is easy to do and can result in hard to track down bugs. Ifvar self = this; is set then passing this is not necessary:

viewmodelself

var self = this; can also help avoid bugs when one binding context refers to another. Consider the following code that displays a list of names. When a user clicks on an name in the list, that name is displayed in the <span> below.

HTML:

html

Javascript:

js

When selectPerson is called its scope is set to the object in person corresponding to the name clicked. However, because var self = this; is set the view model object is still accessible within the event callback. This would not be the case otherwise.

In production code I almost always define var self = this;. However, for the sake of brevity, I won’t use it in some examples in this article.

3 Logic in templates

Knockout makes it easy to write complicated logic in HTML templates. Avoid doing this at all costs! It results in difficult to test and maintain code. Instead of using logic in templates…

computedlogic

4 Testing

Speaking of testing, by default Knockout offers no tools to help you. This does not mean you shouldn’t write tests! There are ample JS testing frameworks, and you should be able to pick up and drop any of them into your Knockout application. As with anything, the earlier you start writing tests the better. I usually don’t start a new Knockout project without also including a testing framework.

5 ko.mapping

ko.mapping is a plugin for Knockout that makes working with data fetched from REST endpoints much more enjoyable.

Without ko.mapping, a view model that consumes objects from a REST API might look like this:

    function viewModel() {
        /*
        * Gets data about a person from the server:
        * person = {
        *   firstName: "John",
        *   lastName: "Stewart"
        * }
        */
        var person = getPersonFromServer();

        this.person = {};
        this.person.firstName = ko.observable(person.firstName);
        this.person.lastName = ko.observable(person.lastName);
    }

With ko.mapping the view model is much simpler:

    function viewModel() {
        var person = getPersonFromServer();
        this.person = ko.mapping.fromJS(person);
    }

Want to convert part of the view model back to plain JSON so that you can POST it back to the API? That’s a one-liner too:

    var json = ko.mapping.toJS(this.person);

While ko.mapping is to some degree officially part of Knockout (it’s in the official documentation), it is a separate project that you’ll have to download and include.

It’s also worth nothing that some people prefer the functionally analogousko.viewModel plugin to ko.mapping. ko.mapping has always worked fine for me, but it only seemed fair to link to both. Use one or the other, but don’t use neither!

6 textInput and valueUpdate

This may seem minor, but it’s caused me so many headaches that it’s worth including. Knockout binds the value of input elements a somewhat strange way. To illustrate, let’s say we have an input element and want to update some text on the page in real time as the input’s value changes:

    <input type="text" data-bind="value: myValue">
    Value: <span data-bind="text: myValue"></span>
    function viewModel() {
        this.myValue = ko.observable();
    }

Surprisingly, the above won’t work. The myValue observable (and thus our text in the span) updates whenever the input loses or gains focus, not as it’s value changes. Why? For performance reasons this is how Knockout behaves by default.

To fix this in Knockout 3.2 (current at the time of writing) or newer, use the textInput binding instead of the value binding.

    <input type="text" data-bind="textInput: myValue">

This will provide immediate updates to myValue with the minor caveat that it won’t guarantee that the value attribute of the input is always synced with myValue.

If you are using an older version of Knockout or if you are dead set on using the value binding, then you must use the valueUpdate flag.

    <input type="text" data-bind="value: myValue, valueUpdate='afterkeydown'">

In Knockout 3.2 there are 4 possible values for valueUpdate, each with its own idiosyncrasies:

  • + input – Updates when the value of the element changes. Doesn’t work in IE8-.
  • + keyup – Updates when a keyup event is fired
  • + keypress – Updates when a keypress event is fired.
  • + afterkeydown – Updates as soon as the user starts typing a character. Does not work on all mobile browsers — notably Safari on IOS7.

Using the textInput binding is strongly recommended over using the valueUpdateflag.

7 Don’t repeatedly push into observable arrays

Pushing multiple times into observable arrays can cause significant performance issues with your application:

    function viewModel() {
        var arr = [0, 1, ..., 999];

        this.numbers = ko.observableArray();

        for (var i = 0; i < arr.length; i++) {
            this.numbers.push(arr[i]);
        }
    }

Running the for loop above will cause Knockout to redraw the page 1000 times — one for each push. To avoid this, simply overwrite the old value of our entire array:

    function viewModel() {
        var arr = [0, 1, ..., 999];
        this.numbers = ko.observableArray(arr);
    }

To transform data before putting it into our new array, use ko.utils.arrayMap.

    function Number(number) {
        this.number = number;
    }

    function viewModel() {
        var arr = [0,1, ..., 999];

        // creates an array of Number objects
        this.numbers = ko.observableArray(ko.utils.arrayMap(arr, function(number) {
            return new Number(number)
        }));

    }

To append many items to an existing observable array, exploit the fact that pushaccepts a variable number of arguments and use apply to push them in all at once.

    function viewModel() {
        var arr = [500, 501, ... 999];

        this.numbers = ko.observableArray([0, 1, ..., 499]);
        this.numbers.push.apply(self.numbers, arr);
    }

8 Observable arrays don’t automatically have observable members

Observable arrays track changes to which objects are in the array. They do not track changes to the state of those objects.

    <ul data-bind="foreach: people">
        <li data-bind="text: name"></li>
    </ul>
    <button data-bind="click: makeDerekMike">Make Derek Mike</button>
    function viewModel() {
        var self = this;

        self.people = ko.observableArray([
            {
                name: 'Derek',
            },
            {
                name: 'Sara'
            },
            ...
        ]);

        self.makeDerekMike = function() {
            for (var i = 0; i < self.people().length; i++) {
                if (self.people()[i].name === 'Derek') {
                    self.people()[i].name = 'Mike';
                }
            }
        };
    }

Clicking the button in the first example will not trigger a page refresh despite the fact that it will modify an object in the array underlying people. This is because the same objects still belong topeople. To trigger a page refresh, we need to explicitly make the fields of the elements in people observable:

    function viewModel() {
        var self = this;

        self.people = ko.observableArray([
            {
                name: ko.observable('Derek')
            },
            {
                name: ko.observable('Sara')
            },
            ...
        ]);

        self.makeDerekMike = function() {
            for (var i = 0; i < self.people().length; i++) {
                if (self.people()[i].name() === 'Derek') {
                    self.people()[i].name('Mike');
                }
            }
        };
    }

9 Components

Because Knockout makes building interactive widgets so simple, it’s easy to write similar code in different parts of your application. Use Knockout components to abstract common UI widgets and promote code reuse.

Using components, we can build a simple reusable list builder as follows:

    <span>This is a list with no initial values</span>
    <div data-bind="component: 'list-builder'"></div>

    <span>This is a list with some initial values</span>
    <div data-bind="component: {
        name: 'list-builder',
        params: { list: ['item', 'another item'] }
    }"></div>
    function Item(text) {
        this.text = text;
    }

    ko.components.register('list-builder', {
        viewModel: function(params) {
            var self = this;

            self.list = ko.observableArray([]);

            if (params && params.list) {
                self.list(ko.utils.arrayMap(params.list, function(item) {
                    return new Item(text);
                }));
            }

            self.newText = ko.observable();
            self.add = function() {
                self.list.push(new Item(text));
                self.newText('');
            };
        },
        template:
            '<ul data-bind="foreach: list">' +
                '<li data-bind="text: text"></li>' +
            '</ul>' +
            '<input type="text" data-bind="textInput: newText" />' +
            '<button data-bind="click: add">Add</button>'
    });

Note that you probably don’t want to inline the viewModel and template as above in any production code code. Fortunately, this can be solved using require.js (see #1). For a description of how to do this check out the official components documentation.

10 Tutorials

Knockout the official tutorials are great! They offer a interactive sandbox to play around with the framework in a guided fashion.