Skip to content

Commit

Permalink
Add factory to view mappings
Browse files Browse the repository at this point in the history
Resolves #50
  • Loading branch information
creynders committed Sep 12, 2014
1 parent 221af79 commit 5d479cc
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 9 deletions.
23 changes: 14 additions & 9 deletions backbone.geppetto.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@
return new FactoryFunction();
}

function createFactory(clazz) {
return function() {
return applyToConstructor(clazz, _.toArray(arguments));
};
}

var Resolver = function(context) {
this._mappings = {};
this._context = context;
Expand Down Expand Up @@ -89,18 +95,17 @@
return output;
},

_wrapConstructor: function(OriginalConstructor, wiring) {
if (OriginalConstructor.prototype.initialize) {
var context = this._context;

return OriginalConstructor.extend({
initialize: function() {
_wrapConstructor: function(clazz, wiring) {
var context = this._context;
if (clazz.extend) {
return clazz.extend({
constructor: function() {
context.resolver.resolve(this, wiring);
OriginalConstructor.prototype.initialize.apply(this, arguments);
clazz.prototype.constructor.apply(this, arguments);
}
});
} else {
return OriginalConstructor;
return clazz;
}
},

Expand Down Expand Up @@ -143,7 +148,7 @@

wireView: function(key, clazz, wiring) {
this._mappings[key] = {
clazz: this._wrapConstructor(clazz, wiring),
clazz: createFactory(this._wrapConstructor(clazz, wiring)),
object: null,
type: TYPES.VIEW
};
Expand Down
23 changes: 23 additions & 0 deletions specs/src/resolver-specs.js
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,29 @@ define([
context.dispatch('event:foo');
expect(contextEventSpy).to.have.been.called;
});
it("should be a factory method (as well)", function(){
var factory = resolver.getObject(key);
var view = factory();
expect(view).to.be.instanceOf(clazz);
});
it("should call the factory view's original 'initialize' function when instantiated", function() {
var initializeSpy = sinon.spy();
expect(initializeSpy).not.to.have.been.called;
clazz.prototype.initialize = function() {
initializeSpy();
};
var factory = resolver.getObject(key);
var viewInstance = factory();
expect(initializeSpy).to.have.been.calledOnce;
});
it("should be injected with its dependencies when instantiated by the factory", function() {
clazz.prototype.wiring = ['foo'];
var foo = {};
resolver.wireValue('foo', foo);
var factory = resolver.getObject(key);
var viewInstance = factory();
expect(viewInstance.foo).to.equal(foo);
});
});
describe("when wrapping a constructor", function() {
it("should allow wrapped constructor to handle initialization parameters in similar fashion as unwrapped constructor)", function() {
Expand Down

0 comments on commit 5d479cc

Please sign in to comment.