본문 바로가기

프로그래밍(TA, AA)/자바스크립트

[자바스크립트] 알아두면 좋은 패턴

Must Know Patterns


Constructor Pattern: In JavaScript almost everything is an object. We often need to create objects. There are 2 ways to create object. (1) object literal notation. (2) Using new operator.


Modular  Pattern: This is used to emulate the concept of classes in JavaScript. A class/module in JavaScript is coded with the help of function expressions. This helps to break code in modules such that some of the variables and methods are private to the modules and other are public and exposed as API to other modules.


Publish/Subscribe: PubSub promotes lose coupling and is easier to scale.  One thing to keep in mind that since subscribers and publishers are loosely coupled, if any subscriber fails due to any any exception the publisher won't even know.

var events = (function(){
	var topics = {};
	var hOP = topics.hasOwnProperty;

	return {
		subscribe: function(topic, listener) {
			// Create the topic's object if not yet created
			if(!hOP.call(topics, topic)) topics[topic] = [];

			// Add the listener to queue
			var index = topics[topic].push(listener) - 1;
			
			// Provide handle back for removal of topic
			return {
				remove: function() {
					delete topics[topic][index];
				}
			}
		},
		publish: function(topic, info) {
			// If the topic doesn't exist, or there's no listners in queue, just leave
			if(!hOP.call()) return;
			
			// Cycle through topics queue, fire!
			topics[topic].forEach(function(item) {
				item(info != undefined ? info : {});
			});
		}
	}
})();


// Publishing to a topic
events.publish("/page/load", {
	url: "/some/url/path"	// any argument
});


// and subscribing to said topic in order to be notified of events
var subscription = events.subscribe('/page/load', function(obj){
	// Do something now that the event has occured
});

subscription.remove();


MVC: MVC is one of the most important design pattern to understand in today's JavaScript world. The system is divided into three components Model, View and Controller.  Model–view–controller



Good to Know Patterns


Flux: This is an architecture promoted by Facebook. This is mostly used with React library but it is an architecture and not coupled with React. This promoted unidirectional flow of data and makes it easy to reason about the state of application at any point of time.