martedì, gennaio 22, 2008

[jsn]A simple JS IoC example code

Inspired by Ninject documentation I decided to port the c# example code to my JS IoC.
Here are the code:

shuriken = {
hit:function(who){alert("pierced the "+who+" armor");}

sword = {
hit:function(who){alert("Chopped the "+who+" in half");}

function Samurai(weapon){
return {
var warrior1 = container.byConstructor("samurai",shuriken),
warrior2 = container.byConstructor("samurai",sword);

warrior1.Attack("The evildoers");
warrior2.Attack("The evildoers");

So simple, So clear!

2 commenti:

Nate Kohari ha detto...

I like it. :) Nice idea for IoC in JavaScript, also!

Unknown ha detto...

I'm glad you liked your example in javascript ;D

I like the way Ninject use the attributes for injection declaration, in javascript this is not possible.
I think that "IoC by hand" is the best way to achieve IoC in js , altough is possible to use XML(or json) like I've done here (I keep it simple and way incomplete because doing so i avoided explaination ;D ):

using xml/json can be good for plugins
implementation in javascript so IoC can be useful,
even if in js there is not a real coupling