Dynamic creation of variable number of instances using wire

15 views
Skip to first unread message

julian

unread,
Oct 5, 2013, 8:51:03 PM10/5/13
to
hi,

i have a use case that i don't know how to fit with the way wire works.  

var Episode = function (name) {
 
this.name = name;
};

var Episodes = function (){};
Episodes.prototype = {
    readFromLocalStorage
: function () {
       
var storedEpisodes;
       
this._list = [];
       
// ... some code here to read data from storage into storedEpisodes.
       
for (var i=0; i<storedEpisodes.length; ++i) {
           
this._list.push(new Episode(storedEpisodes[i].name))
       
}
   
}
}

i'm stumped on how to use wire here to remove the direct knowledge that Episodes has of Episode.

hope that's clear.

thanks in advance.

julian

Brian Cavalier

unread,
Oct 5, 2013, 10:24:28 PM10/5/13
to cuj...@googlegroups.com
Hi Julian,

Good question.  There are a few ways you might do it, and which one is best probably depends on your situation.

One simple approach is to inject the particular episode constructor you want to use.  For example, if you have Episodes as it's own module, and are already using wire to create an instance of it, you could inject the particular constructor it should use to create new Episode instances.  Here's a gist:


There are variants on that, such as injecting the particular episode constructor via an argument to the Episodes constructor.  You could also have the Episodes.prototype.EpisodeType default to something if you want.  However, that would re-introduce a hard dependency on whatever it defaults to!

The extra indirection via createEpisode in the first example function isn't strictly necessary, but it can be nice to throw there so that things fail fast when someone forgets to inject an episode constructor.  If that bugs you :) it would be another reason to use a constructor argument as opposed to property injection.

There are other approaches, such as setting up a deferred wire function to create new instances.  That would allow for more sophisticated configuration of new episode instances, but would also introduce the need to deal with promises in the Episodes module.  Let me know if that sounds interesting, and I'll be happy to whip up an example.

Hope that helps. Let me know if that works for you!

julian

unread,
Oct 5, 2013, 11:16:19 PM10/5/13
to cuj...@googlegroups.com
hi, brian.

thanks so much for the explanation and code examples.
both are great solutions, though i'm partial to the constructor-injected one.
i am actually familiar with, and already using, promises (cujojs' when).  so, yes, i'd be very interested in learning how to use promises in wiring.
thanks again! 
Reply all
Reply to author
Forward
0 new messages