Javascript - Observer Pattern

javascript

Another excellent pattern is the Observer Pattern – sometimes referred to as “Pubsub.” Pubsub essentially allows us to subscribe to DOM events, such as click and mouseover. On one hand, we’re listening to these events, and, on the other, something is publishing those events – for example, when the browser publishes (or announces) that someone clicked on a particular element. One solid choice is AmplifyJS.

// A data model for retrieving news.
NS.Models.News = (function () {
    var newsUrl = '/news/'

    // Retrieve the news
    var getNews = function () {
        $.ajax({
            url: newsUrl
            type: 'get',
            success: newsRetrieved
        });
    };

    var newsRetrieved = function (news) {
        // Publish the retrieval of the news
        amplify.publish('news-retrieved', news);
    };

    return {
        getNews: getNews
    };
}());

This code defines a model to fetch news from some kind of service. Once the news has been retrieved with AJAX, the newsRetrieved method fires, passing through the retrieved news to Amplify, and is published on the news-retrieved topic.

(function () {
    // Create a news views.
    NS.Views.News = function () {
        this.news = $('#news');

        // Subscribe to the news retrieval event.
        amplify.subscribe('news-retrieved', $.proxy(this.showNews));
    };

    // Show the news when it arrives
    NS.Views.News.prototype.showNews = function (news) {
        var self = this;
        $.each(news, function (article) {
            self.append(article);
        });
    };
}());

This code above is a view for displaying the retrieved news. In the News constructor, Amplify subscribes to the news-retrieved topic. When that topic is published, the showNews function is fired, accordingly. Then, the news is appended to the DOM.

// Modify this the App.init above
var init = function () {
    NS.Utils.log('Application initialized...');
    this.welcome = new NS.Views.WelcomeScreen();
    this.welcome.showWelcome();

    this.news = new NS.Views.News();

    // Go get the news!
    NS.Models.News.getNews();
};

Again, modify the init function from the app to add the news retrieval… and you’re done! Now, there are separate pieces of the application, each of which is responsible for a single action. This is known as the Single Responsibility Principle.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License