Skip to content

Comment on The Strategy Pattern in JavaScript

Comments

Tell me if I have this straight: this pattern basically says to create a generic object with properties and handlers to allow for simple iteration, creation, etc. like you would with an interface. Then, if needed, use a prototype to set defaults?

Pretty much. I'm using this pattern in the following way:

SomeComponent.prototype.views = { home: { template: '/path/to/template', render: function(tmpl) { this.element.html(Mustache.to_html(tmpl, this.data)); } } };

I then have SomeComponent inherit the prototype of Component which has a generic render method. When I call the render method on any given component, it will have some logic to figure out which view it is in, then call the render method specific to that view with the correct template, that it fetches the content of under-the-hood.

Having consistent and expected behavior in your code is a huge win.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.