keepyourweb
keepyourweb

Reputation: 1

jquery and observer pattern

I started to use the pattern observer for develop my jQuery applications, but sincerely I don't understand the benefits of this pattern.

Example:

myfunctions = {
    first_function: function() {
        alert('This is the first function');
    },
    second_function: function() {
        alert('This is the second function');
    }
};

Now, why this method:

$(document).bind({
    'first_function': myfunctions.first_function,
    'second_function': myfunctions.second_function
});

$('button').bind('click', function() {
    $(document).trigger('first_function');
});

is better than this:

$('button').click(function() {
    myfunctions.first_function();
});

Upvotes: 0

Views: 855

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385194

Well, in your contrived case, it isn't.

When your code grows, it is. It's more scalable.

Upvotes: 0

Antony Scott
Antony Scott

Reputation: 21998

The observer pattern is useful when you have something of "interest" to other 'things', but you don't know exactly how many or even what those 'things' might be.

I implemented the observer pattern some years ago in javascript for a "dashboard" style page, where a number of controls (at the top of the page) were used by various panels. Those panels needed to refresh if one or more of those controls had their value changed. It worked great, as I could add new panels and set them up as observers of any of the "top" controls without the controls needing to know about the new panels.

Upvotes: 3

Related Questions