Yammer integrations in ReactJS

By | Front-end, Javascript, React.js, Redux, Webpack, Yammer | No Comments


I am writing this blog while I am working on a project for our client’s intranet website. The client requires the website has the ability to share, like and write comments in the website through a social media channel called Yammer (https://www.yammer.com/) which is created by Microsoft.

I have never used or even heard about Yammer before. By the first look at the user interface and functionalities it provides, I thought it is just a Facebook-like product for enterprise to use internally.

The main framework for the frontend I use for this project is React + Redux which is built with Babel, Webpack and ES6. The website itself is nothing magic but a painful to deal with a lot of security staff (VPN, Azure authentication etc) which takes me a lot of time and I am not going to discuss them here today.

Back to Yammer, when I looked at the documentation(https://developer.yammer.com/docs), I found it is really poorly written with only a few example code that you can follow, compared with Facebook and Twitter. There is no official git repository available either. It made me hard to work on, someone who has no experience working with Yammer before, especially in ReactJS.

To integrate with Yammer, there are two possible ways that you can enable its features in your client side: REST API and Javascript embeded widget. By read through the documentations, I found both have pros and cons:


  • Be able to fully customize UI
  • Can do like, comments and other functions which are not available in embedded javascript widget
  • Easy to code with frontend framework
  • Time consuming. To make it works properly, for instance, commenting, you are almost rebuilding the new widget.
  • No ‘share’ endpoint available in REST API

Yammer Embedded Widget

  • Very easy to use in the current code base and not much work to do
  • Good integrations for share and commenting feature
  • Documents are poor with no explanation on each params of the widgets
  • Use iframe for ‘like’
  • No ‘number of likes’ available in the ‘like’ widget
  • Can’t change the look of the ‘like’ button easily
  • No official NPM module currently available from Microsoft Yammer team’s answer

By comparing the approaches above, our team made the decision to use them as a combination:

  • Use REST API for ‘like’ feature due to the lack of support by Yammer widget
  • Use Embedded widget for ‘share’ and ‘commenting’ features to save time and make sure the project can be done within the tight timeframe.

However, as I have said, there is no official NPM modules available for Yammer so far. It made me feel really frustrated to use the library in React component. I tried different ways to import the library from Webpack but none of them work. For your interest, this is the one I have tried https://www.npmjs.com/package/script-loader.

Finally, I found a solution which is inspired by Ambroos. The solution is to use a library which can easily load an external library into ReactJS component and finally solve my problem.

The library is called scriptjs – https://www.npmjs.com/package/scriptjs and it is really easy it use as follows in my code:

import $scriptjs from 'scriptjs';
componentDidUpdate() {
//script loader
let _self = this;
$scriptjs('https://c64.assets-yammer.com/assets/platform_embed.js', function(){
}, 1000);

In this way, you can refer the global yam object with ‘window.yam’ and call its functions in the callback. This code above does load the Yammer feeds widget every time the current component gets updated. Of course, like the other NPM modules, you need to run ‘npm install scriptjs’ first before you can use it in your ReactJS component.

I don’t think this is best practice to use Yammer library in ReactJS, but at least it can solve my problem, pain in the easiest way without putting too much effort in it and change much of my code.

What’s the difference between Bower and NPM?

By | Bower, Front-end, NPM | No Comments

What is the fundamental difference between Bower and npm?

npm is most commonly used for managing Node.js modules, but it works for the front-end too when combined with Browserify.

Bower is created solely for the front-end and is optimized with that in mind. The biggest difference is that npm does nested dependency tree (size heavy) while Bower requires a flat dependency tree(puts the burden of dependency resolution on the user).

A nested dependency tree means that your dependencies can have its own dependencies which can have their own, and so on. This is really great on the server where you don’t have to care much about space and latency. It lets you not have to care about dependency conflicts as all your dependencies use e.g. their own version of Underscore. This obviously doesn’t work that well on the front-end. Imagine a site having to download three copies of jQuery.

The reason many projects use both is that they use Bower for front-end packages and npm for developer tools like Yeoman, Grunt, Gulp, JSHint, CoffeeScript, etc.

All package managers have many downsides. You just have to pick which you can live with.

5 Grunt Tasks that Improve the Performance of Your Website

By | Grunt.js, Javascript | 2 Comments

Many times on SitePoint I’ve mentioned how achieving good performance is a main concern today and how you should strive for fast web pages. In some articles of mine about JavaScript APIs, such as Introduction to the Resource Timing API and Discovering the User Timing API, I gave you all the power you need to know what’s slowing down your project. Earlier this year, Craig Buckler covered this topic too, with his article The Complete Guide to Reducing Page Weight.

If you aren’t stuck in the past, you’re likely using a task runner like Grunt or Gulp to improve your workflow by automating a lot of operations we used to perform manually. In this article I’ll describe five Grunt tasks that help us enhance the performance of our web pages.


The first task I want to mention is grunt-contrib-imagemin. The reason why I want to discuss it first is that images are killing the web. Seriously!

If you take a look at HTTParchive.org statistics you’ll see that images represent more than 63% of the total size of a page. The reason for such bloat is that often images aren’t compressed to have a weight as low as possible. grunt-contrib-imagemin is one of the tasks you can use to solve this issue.

This task comes with the following optimizers to be able to compress most of the image formats employed on the web:

  • gifsicle to compress GIF images
  • jpegtran to compress JPEG images
  • optipng to compress PNG images
  • svgo to compress SVG images


The grunt-contrib-uglify task is used to minify JavaScript files. This task removes all the unnecessary whitespace that your source code has, and renames the variables and functions consistently to use a name as short as possible.

Some options that you’ll often use for this task are sourceMap and banner. The former creates a source map file in the same directory as the destination file. To enable this option you have to set it to true. Banner is a string to prepend to the minified output in which you usually write the name of the file/library/framework, its version, your name as the author, and the license. Its default value is an empty string.


As the name suggests, grunt-contrib-cssmin compresses CSS files. Like the grunt-contrib-uglify task, this one provides a banner option.


Another task that deals with CSS is grunt-uncss. This task removes unused CSS from a project, so it reduces the size of the final CSS file, and thus improves the download time. It’s particularly well suited if you’re developing using a framework like Boostrap or Foundation. This task has some important limitations that you can read on the official documentation.

Some nice options worth mentioning are ignore, that allows us to specify a list of selectors that should not be removed, and ignoreSheets, that allows us to specify style sheets to ignore.


The last Grunt task I want to discuss in this article is grunt-contrib-htmlmin, a task to minify HTML code. It doesn’t speed up your website a lot because it often saves just a few Kbs, and if you’re serving your content using gzip compression, the gain is even lower. Therefore, if you’re looking to minify your HTML, well… compliments; it means your website was already pretty optimized.

Nonetheless, the philosophy to follow when dealing with performance on the web is that every Kb counts. So, let’s see a simple configuration that integrates this task into our workflow:


In this article I introduced you to five Grunt tasks to easily improve the performance of your website. They’re so simple that you really have no excuses to avoid using them and offer your users a better experience through a faster service. I hope you liked this article and you’ll employ these tasks soon.

Have you ever used them? How much did they improve your website? Are there any tasks you love and want to share with us?

How to use AngularJS and Laravel Blade together

By | Javascript | No Comments

The problem

When it comes to making AngularJS and Laravel Blade work together, there is only one real problem. Both AngularJS and Laravel Blade use double curly brackets for opening and closing tags. Luckily there is a quick and painless solution for this problem!

The solution

The solution for making AngularJS and Laravel Blade work together is simple. We can simply use Angular’s $interpolateProvider to change the tags.

In short: we want to change the tags of AngularJS to anything other than double curly brackets, for example a double percentage sign.

Example code would be:

var customInterpolationApp = angular.module('customInterpolationApp', []);
customInterpolationApp.config(function($interpolateProvider) {

You can now freely use %% for AngularJS and the usual {{ and }} for Laravel Blade!
If you liked this quick little tip, please share it on TwitterFacebookStumbleUpon, …

Thank you for reading!

Struggling with npm install

By | Javascript | No Comments

Today, I was trying to install Yeoman (highly recommend for AngularJS & web app developing) on my home iMac. I downloaded NodeJS, installed and then enter the commend:

npm install -g yo

Then the nightmare just happened that I got so many errors like hell.

I finally found the solution which needs to follow the steps:

1. [sudo] rm -rf /usr/local/lib/node_modules/yo

2. npm cache clear

3. npm install -g yo

And now Yeoman is successfully installed.

JavaScript Module Pattern: In-Depth

By | Javascript | 2 Comments

The module pattern is a common JavaScript coding pattern. It’s generally well understood, but there are a number of advanced uses that have not gotten a lot of attention. In this article, I’ll review the basics and cover some truly remarkable advanced topics, including one which I think is original.

The Basics

We’ll start out with a simple overview of the module pattern, which has been well-known since Eric Miraglia (of YUI) firstblogged about it three years ago. If you’re already familiar with the module pattern, feel free to skip ahead to “Advanced Patterns”.

Anonymous Closures

This is the fundamental construct that makes it all possible, and really is the single best feature of JavaScript. We’ll simply create an anonymous function, and execute it immediately. All of the code that runs inside the function lives in a closure, which provides privacy and state throughout the lifetime of our application.

(function () {
	// ... all vars and functions are in this scope only
	// still maintains access to all globals

Notice the () around the anonymous function. This is required by the language, since statements that begin with the tokenfunction are always considered to be function declarations. Including () creates a function expression instead.

Global Import

JavaScript has a feature known as implied globals. Whenever a name is used, the interpreter walks the scope chain backwards looking for a var statement for that name. If none is found, that variable is assumed to be global. If it’s used in an assignment, the global is created if it doesn’t already exist. This means that using or creating global variables in an anonymous closure is easy. Unfortunately, this leads to hard-to-manage code, as it’s not obvious (to humans) which variables are global in a given file.

Luckily, our anonymous function provides an easy alternative. By passing globals as parameters to our anonymous function, we import them into our code, which is both clearer and faster than implied globals. Here’s an example:

(function ($, YAHOO) {
	// now have access to globals jQuery (as $) and YAHOO in this code
}(jQuery, YAHOO));

Module Export

Sometimes you don’t just want to use globals, but you want to declare them. We can easily do this by exporting them, using the anonymous function’s return value. Doing so will complete the basic module pattern, so here’s a complete example:

var MODULE = (function () {
	var my = {},
		privateVariable = 1;

	function privateMethod() {
		// ...

	my.moduleProperty = 1;
	my.moduleMethod = function () {
		// ...

	return my;

Notice that we’ve declared a global module named MODULE, with two public properties: a method namedMODULE.moduleMethod and a variable named MODULE.moduleProperty. In addition, it maintains private internal stateusing the closure of the anonymous function. Also, we can easily import needed globals, using the pattern we learned above.

Advanced Patterns

While the above is enough for many uses, we can take this pattern farther and create some very powerful, extensible constructs. Lets work through them one-by-one, continuing with our module named MODULE.


One limitation of the module pattern so far is that the entire module must be in one file. Anyone who has worked in a large code-base understands the value of splitting among multiple files. Luckily, we have a nice solution to augment modules. First, we import the module, then we add properties, then we export it. Here’s an example, augmenting our MODULE from above:

var MODULE = (function (my) {
	my.anotherMethod = function () {
		// added method...

	return my;

We use the var keyword again for consistency, even though it’s not necessary. After this code has run, our module will have gained a new public method named MODULE.anotherMethod. This augmentation file will also maintain its own private internal state and imports.

Loose Augmentation

While our example above requires our initial module creation to be first, and the augmentation to happen second, that isn’t always necessary. One of the best things a JavaScript application can do for performance is to load scripts asynchronously. We can create flexible multi-part modules that can load themselves in any order with loose augmentation. Each file should have the following structure:

var MODULE = (function (my) {
	// add capabilities...

	return my;
}(MODULE || {}));

In this pattern, the var statement is always necessary. Note that the import will create the module if it does not already exist. This means you can use a tool like LABjs and load all of your module files in parallel, without needing to block.

Tight Augmentation

While loose augmentation is great, it does place some limitations on your module. Most importantly, you cannot override module properties safely. You also cannot use module properties from other files during initialization (but you can at run-time after intialization). Tight augmentation implies a set loading order, but allows overrides. Here is a simple example (augmenting our original MODULE):

var MODULE = (function (my) {
	var old_moduleMethod = my.moduleMethod;

	my.moduleMethod = function () {
		// method override, has access to old through old_moduleMethod...

	return my;

Here we’ve overridden MODULE.moduleMethod, but maintain a reference to the original method, if needed.

Cloning and Inheritance

var MODULE_TWO = (function (old) {
	var my = {},

	for (key in old) {
		if (old.hasOwnProperty(key)) {
			my[key] = old[key];

	var super_moduleMethod = old.moduleMethod;
	my.moduleMethod = function () {
		// override method on the clone, access to super through super_moduleMethod

	return my;

This pattern is perhaps the least flexible option. It does allow some neat compositions, but that comes at the expense of flexibility. As I’ve written it, properties which are objects or functions will not be duplicated, they will exist as one object with two references. Changing one will change the other. This could be fixed for objects with a recursive cloning process, but probably cannot be fixed for functions, except perhaps with eval. Nevertheless, I’ve included it for completeness.

Cross-File Private State

One severe limitation of splitting a module across multiple files is that each file maintains its own private state, and does not get access to the private state of the other files. This can be fixed. Here is an example of a loosely augmented module that willmaintain private state across all augmentations:

var MODULE = (function (my) {
	var _private = my._private = my._private || {},
		_seal = my._seal = my._seal || function () {
			delete my._private;
			delete my._seal;
			delete my._unseal;
		_unseal = my._unseal = my._unseal || function () {
			my._private = _private;
			my._seal = _seal;
			my._unseal = _unseal;

	// permanent access to _private, _seal, and _unseal

	return my;
}(MODULE || {}));

Any file can set properties on their local variable _private, and it will be immediately available to the others. Once this module has loaded completely, the application should call MODULE._seal(), which will prevent external access to the internal _private. If this module were to be augmented again, further in the application’s lifetime, one of the internal methods, in any file, can call _unseal() before loading the new file, and call _seal() again after it has been executed. This pattern occurred to me today while I was at work, I have not seen this elsewhere. I think this is a very useful pattern, and would have been worth writing about all on its own.


Our final advanced pattern is actually the simplest. There are many good cases for creating sub-modules. It is just like creating regular modules:

MODULE.sub = (function () {
	var my = {};
	// ...

	return my;

While this may have been obvious, I thought it worth including. Sub-modules have all the advanced capabilities of normal modules, including augmentation and private state.


Most of the advanced patterns can be combined with each other to create more useful patterns. If I had to advocate a route to take in designing a complex application, I’d combine loose augmentationprivate state, and sub-modules.

I haven’t touched on performance here at all, but I’d like to put in one quick note: The module pattern is good for performance. It minifies really well, which makes downloading the code faster. Using loose augmentation allows easy non-blocking parallel downloads, which also speeds up download speeds. Initialization time is probably a bit slower than other methods, but worth the trade-off. Run-time performance should suffer no penalties so long as globals are imported correctly, and will probably gain speed in sub-modules by shortening the reference chain with local variables.

To close, here’s an example of a sub-module that loads itself dynamically to its parent (creating it if it does not exist). I’ve left out private state for brevity, but including it would be simple. This code pattern allows an entire complex heirarchical code-base to be loaded completely in parallel with itself, sub-modules and all.

var UTIL = (function (parent, $) {
	var my = parent.ajax = parent.ajax || {};

	my.get = function (url, params, callback) {
		// ok, so I'm cheating a bit :)
		return $.getJSON(url, params, callback);

	// etc...

	return parent;
}(UTIL || {}, jQuery));

I hope this has been useful, and please leave a comment to share your thoughts. Now, go forth and write better, more modular JavaScript!


In ObjectiveC, What is the difference between class and instance methods?

By | iOS, mobile technology, Objective-C | No Comments

 instance methods use an instance of a class, whereas a class method can be used with just the class name. In Objective-C they are defined thusly:


They could then be used like so:

[MyClass aClassMethod];MyClass*object =[[MyClass alloc] init];[object anInstanceMethod];

Some real world examples of class methods are the convenience methods on many Foundation classes like NSString‘s +stringWithFormat: or NSArray‘s +arrayWithArray:. An instance method would be NSArray‘s -count method.

Understand Backbone.js REST calls

By | Javascript | No Comments

The HTTP Protocol

I like examples, so here is an HTTP request to get the HTML for this page:

GET /questions/18504235/understand-backbone-js-rest-calls HTTP/1.1Host: stackoverflow.com

[Optional] If you have ever played with command line or terminal, try running the command telnet stackoverflow.com 80 and pasting in the above, followed by pressing enter a couple of times. Voila! HTML in all of it’s glory.

In this example…

  • GET is the method.
  • /questions/18504235/understand-backbone-js-rest-calls is the path.
  • HTTP/1.1 is the protocol.
  • Host: stackoverflow.com is an example of a header.

Your browser does approximately the same, just with more headers, in order to get the HTML for this page. Cool, huh?

Since you work in front end, you’ve probably seen the form tag many times. Here’s an example of one:

<formaction="/login"method="post"><inputtype="text"name="username"/><inputtype="password"name="password"/><inputtype="submit"name="submit"value="Log In"/></form>

When you submit this form along with appropriate data, your browser sends a request that looks something like this:

POST /login HTTP/1.1Host: stackoverflow.com


There are three differences between the previous example and this one.

  1. The method is now POST.
  2. The path is now /login.
  3. There is an extra line, called the body.

While there are a bunch of other methods, the ones used in RESTful applications are POSTGETPUT, and DELETE. This tells the server what type of action it’s supposed to take with the data, without having to have different paths for everything.

Back to Backbone

So hopefully now you understand a bit more about how HTTP works. But how does this relate to Backbone? Let’s find out!

Here’s a small chunk of code you might find in a Backbone application.

    model:BookModel, url:'/books'});

Create (POST)

Since we’re using a RESTful API, that’s all the information Backbone needs to be able to create, read, update, and delete all of our book information! Let’s start by making a new book. The following code should suffice:

var brandNewBook =newBookModel({ title:'1984', author:'George Orwel'});

Backbone realizes you’re trying to create a new book, and knows from the information it’s been given to make the following request:

POST /books HTTP/1.1Host: example.com

{"title":"1984","author":"George Orwel"}

Read (GET)

See how easy that was? But we want to get that information back at some point. Let’s say we ran new BookCollection().fetch(). Backbone would understand that you’re trying to read a collection of books, and it would make the following request:

GET /books HTTP/1.1Host: example.com

BAM. That easy. But say we only wanted the information for one book. Let’s say book #42. Say we ran new BookModel({ id: 42 }).fetch(). Backbone sees you’re trying to read a single book:

GET /books/42 HTTP/1.1Host: example.com

Update (PUT)

Oh darn, I just realized I spelled Mr. Orwell’s name wrong. Easy to fix!

brandNewBook.set('author','George Orwell');

Backbone is smart enough to know that despite being called brandNewBook, it’s already been saved. So it updates the book:

PUT /books/84 HTTP/1.1Host: example.com

{"title":"1984","author":"George Orwell"}

Delete (DELETE)

Finally, you realize that the government is tracking your every move, and you need to bury the fact that you have read 1984. It’s probably too late, but it never hurts to try. So you run brandNewBook.destroy(), and Backbone becomes sentient and realizes your danger deletes the book with the following request:

DELETE /books/84 HTTP/1.1Host: example.com

And it’s gone.