06.07.2017 Views

Mastering JavaScript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5<br />

var TweetFollower = {<br />

update : function() {<br />

console.log( '"Following this tweet - ', arguments );<br />

}<br />

};<br />

Both these observers will have one update() method that will be called by the<br />

Subject.notify() method. Now we can actually add these observers to the<br />

Subject via Tweeter's interface:<br />

var tweetApp = new Tweeter();<br />

tweetApp.addObserver( TweetUpdater );<br />

tweetApp.addObserver( TweetFollower );<br />

tweetApp.fetchTweets();<br />

tweetApp.removeObserver(TweetUpdater);<br />

tweetApp.removeObserver(TweetFollower);<br />

This will result in the following output:<br />

Added observer<br />

Added observer<br />

Updated Tweet - { '0': [ { tweet: 'This is one nice observer' } ] }<br />

"Following this tweet - { '0': [ { tweet: 'This is one nice<br />

observer' } ] }<br />

Removed Observer<br />

Removed Observer<br />

This is a basic implementation to illustrate the idea of the observer pattern.<br />

<strong>JavaScript</strong> Model-View-* patterns<br />

Model-View-Controller (MVC), Model-View-Presenter (MVP), and Model-View-<br />

ViewModel (MVVM) have been popular with server applications, but in recent<br />

years <strong>JavaScript</strong> applications are also using these patterns to structure and manage<br />

large projects. Many <strong>JavaScript</strong> frameworks have emerged that support MV*<br />

patterns. We will discuss a few examples using Backbone.js.<br />

Model-View-Controller<br />

MVC is a popular structural pattern where the idea is to divide an application into<br />

three parts so as to separate the internal representations of information from the<br />

presentation layer. MVC consists of components. The model is the application object,<br />

view is the presentation of the underlying model object, and controller handles the<br />

way in which the user interface behaves, depending on the user interactions.<br />

[ 139 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!