Skip to content

Commit

Permalink
Use an IIFE as callback to replace.
Browse files Browse the repository at this point in the history
Without the IIFE, 'passed' is just a reference and could potentially
change before the function is called leading to unexpected behaviour.
  • Loading branch information
Billy Monk committed Dec 16, 2014
1 parent c9be6a2 commit 5c9cd52
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 3 deletions.
8 changes: 5 additions & 3 deletions js/foundation/foundation.interchange.js
Expand Up @@ -126,15 +126,17 @@

if (passed) {
this.settings.directives[passed
.scenario[1]].call(this, passed.el, passed.scenario[0], function () {
.scenario[1]].call(this, passed.el, passed.scenario[0], (function (passed) {
if (arguments[0] instanceof Array) {
var args = arguments[0];
} else {
var args = Array.prototype.slice.call(arguments, 0);
}

passed.el.trigger(passed.scenario[1], args);
});
return function() {
passed.el.trigger(passed.scenario[1], args);
}
}(passed)));
}
}
}
Expand Down
43 changes: 43 additions & 0 deletions spec/interchange/interchange.js
Expand Up @@ -70,4 +70,47 @@ describe('interchange:', function() {
expect($('div[data-interchange]').data('data-interchange-last-path')).toMatch(/.+html$/)
});
});

describe('events', function() {
beforeEach(function() {
document.body.innerHTML = __html__['spec/interchange/basic.html'];
Foundation.libs.interchange.cache = {};
});

it('should handle emitting one event', function() {
var callback = jasmine.createSpy('callback');

$('div[data-interchange]').on('replace', callback);

Foundation.libs.interchange.update_nodes();
Foundation.libs.interchange.resize();

expect(callback).toHaveBeenCalled();
});

it('should handle emitting multiple events', function() {
var $element0 = $('div[data-interchange]').attr('id', 'element0'),
$element1 = $element0.clone().attr('id', 'element1').appendTo('body'),
callback0 = jasmine.createSpy('callback0'),
callback1 = jasmine.createSpy('callback1');

$.get.isSpy = false;
spyOn($, 'get').andCallFake(function(path, callback) {
runs(function() {
callback('<h1>TWO EVENTS</h1>')
});
});

$element0.on('replace', callback0);
$element1.on('replace', callback1);

Foundation.libs.interchange.update_nodes();
Foundation.libs.interchange.resize();

runs(function() {
expect(callback0).toHaveBeenCalled();
expect(callback1).toHaveBeenCalled();
});
});
});
});

0 comments on commit 5c9cd52

Please sign in to comment.