0

What I want to do is create an object by doing some xhr requests in the constructor. Is this considered a bad practice?
I'm using jquery promises to attach them to the object in the constructor so I'll have something like this:

obj = new MyObj(params);
obj.done(func)
obj.fail(errFunc)

Which looks good and clean but I'm not sure how good of a practice it is considering that my obj is now both a normal obj on which I set props in the constructor but also a promise.
Other then this, I didn't see any other promises implementation that let's you attach a promise to an existing object (correct me if I'm wrong) in case I want to switch from the jquery implementation.

Quote from jquery doc:

If target is provided, deferred.promise() will attach the methods onto it and then return this object rather than create a new one. This can be useful to attach the Promise behavior to an object that already exists.

Nick Dima
  • 1,587
  • 2
  • 18
  • 36
  • 3
    You can use any promise implementation for what you want to do. You don't need one that *extends* an existing object, the object can just implement the same API (e.g. `.done` and `.fail`) and delegate to the actual promise object. Anyways, I personally wouldn't do that in the constructor. I would create a static factory method, like `MyObj.createInstance(params).done(func)`. – Felix Kling Mar 05 '14 at 17:58
  • Thanks Felix! Can you elaborate a bit on why you would go with the factory method? – Nick Dima Mar 05 '14 at 18:34
  • 2
    Basically if you do `obj = new MyObj(params);` instead, then `obj` is not in a usable state (at least that's how I read your question). You have to wait until `func` is called to actually use the object. This seems error prone, e.g. if you pass the object somewhere else before the data was loaded. Using the factory method encapsulates all of this. You don't have access to the instance before it is ready. – Felix Kling Mar 05 '14 at 18:44
  • You might want to use [a different pattern](http://stackoverflow.com/a/21698440/1048572) – Bergi Jun 20 '14 at 09:56

0 Answers0