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');
}
};开发者_如何学Go
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();
});
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.
Well, in your contrived case, it isn't.
When your code grows, it is. It's more scalable.
精彩评论