Skip to content

Commit

Permalink
Merge pull request #23 from mrjoelkemp/master
Browse files Browse the repository at this point in the history
Fixes #22
  • Loading branch information
mrjoelkemp committed Jan 2, 2014
2 parents fc906e4 + 9cd6d1f commit 202ef96
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 2 deletions.
4 changes: 4 additions & 0 deletions Cocktail.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@
}
_(mixin).each(function(value, key) {
if (_.isFunction(value)) {
// If the mixer already has that exact function reference
// Note: this would occur on an accidental mixin of the same base
if (obj[key] === value) return;

if (obj[key]) {
collisions[key] = collisions[key] || [obj[key]];
collisions[key].push(value);
Expand Down
2 changes: 1 addition & 1 deletion Cocktail.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,10 @@ Whether or not you're monkey patching Backbone, you can also use named mixins by

In the example above, both `MyView` and `SelectMixin` both defined `initialize`, and `render`. What happens with these colliding methods?

Cocktail automatically ensures that methods defined in your mixins do not obliterate the corresponding methods in your classes. This is accomplished by wrapping all colliding methods into a new method that is then assigned to the final composite object.
Cocktail automatically ensures that methods defined in your mixins do not obliterate the corresponding methods in your classes.
This is accomplished by wrapping all colliding methods into a new method that is then assigned to the final composite object.

Note: Cocktail will ensure that if you accidentally try to mix in the same method, it will not result in a collision and will do nothing.

### How are colliding functions called?

Expand Down
28 changes: 28 additions & 0 deletions spec/spec/CocktailSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,34 @@ describe('Cocktail', function() {
view.fooBar();
expect(calls).toEqual(['fooBarOriginal', 'fooBarInclude']);
});

it("should not mixin the same function reference more than once", function () {
var A = {
foo: function () {
console.log('foo');
}
};

var B = {};

var C = {
foo: function () {
console.log('foo');
}
};

Cocktail.mixin(B, A);
expect(B.foo === A.foo).toBeTruthy();

// An accidental mixin of the same base
Cocktail.mixin(B, A);
expect(B.foo === A.foo).toBeTruthy();

// Expect the collision wrapper
Cocktail.mixin(B, C);
expect(B.foo === A.foo).toBeFalsy();
expect(B.foo === C.foo).toBeFalsy();
});
});

describe("when patching backbone", function() {
Expand Down

0 comments on commit 202ef96

Please sign in to comment.