Skip to content

Instantly share code, notes, and snippets.

@radekstepan
Created October 20, 2014 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radekstepan/3cb0f6f44aa28b6b4527 to your computer and use it in GitHub Desktop.
Save radekstepan/3cb0f6f44aa28b6b4527 to your computer and use it in GitHub Desktop.
Listening to events in Ractive
var test = require('tape');
var Ractive = require('ractive');
var _ = require('lodash');
var mediator = require('../src/js/app/modules/mediator.js');
test('mediator subscriptions get cancelled', function(t) {
var called = 0;
var View = Ractive.extend({
'alive': false,
'suscriptions': [],
subscribe: function(name, cb) {
var sub = mediator.on(name, cb);
this.suscriptions.push(sub);
},
onconstruct: function() {
this.alive = true;
// Track how many times we get called.
this.subscribe('!event', function() {
called += 1;
});
},
onteardown: function() {
this.alive = false;
_.forEach(this.suscriptions, function(sub) {
sub.cancel();
});
}
});
var view = new View();
view.render();
t.equal(view.alive, true);
mediator.fire('!event');
t.equal(called, 1);
view.teardown();
mediator.fire('!event');
t.equal(view.alive, false);
t.equal(called, 1);
t.end();
});
// This test fails.
test('Ractive children listen to * events from parents', function(t) {
var called = 0;
var Component = Ractive.extend({
'alive': false,
onconstruct: function() {
this.alive = true;
this.on('*.event!', function() {
called += 1;
});
},
onteardown: function() {
this.alive = false;
}
});
var Parent = Ractive.extend({
'alive': false,
'template': '<Child/>',
'components': {
'Child': Component
},
onconstruct: function() {
this.alive = true;
},
onteardown: function() {
this.alive = false;
}
});
var parent = new Parent(),
child = parent.findComponent('Child');
// Both alive.
t.equal(parent.alive, true);
t.equal(child.alive, true);
// Parent fires event, child listens.
parent.fire('!event');
t.equal(called, 1);
// Destroy child.
child.teardown();
t.equal(child.alive, false);
// Parent fires on the child's grave....
parent.fire('!event');
// ... but there is no reply...
t.equal(called, 1);
t.end();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment