Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bubble events on fire #1117

Merged
merged 17 commits into from
Aug 31, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 6 additions & 15 deletions src/Ractive/prototype/fire.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,10 @@
export default function Ractive$fire ( eventName, event ) {
var args, i, len, originalEvent, stopEvent = false, subscribers = this._subs[ eventName ];
import fireEvent from 'Ractive/prototype/shared/fireEvent';

if ( !subscribers ) {
return;
}
export default function Ractive$fire ( eventName ) {

args = Array.prototype.slice.call( arguments, 1 );
var options = {
args: Array.prototype.slice.call( arguments, 1 )
};

for ( i=0, len=subscribers.length; i<len; i+=1 ) {
if ( subscribers[ i ].apply( this, args ) === false ) {
stopEvent = true;
}
}
if ( stopEvent && ( originalEvent = event.original ) ) {
originalEvent.preventDefault && originalEvent.preventDefault();
originalEvent.stopPropagation && originalEvent.stopPropagation();
}
fireEvent( this, eventName, options );
}
3 changes: 2 additions & 1 deletion src/Ractive/prototype/reset.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import fireEvent from 'Ractive/prototype/shared/fireEvent';
import runloop from 'global/runloop';
import Fragment from 'virtualdom/Fragment';
import config from 'config/config';
Expand Down Expand Up @@ -78,7 +79,7 @@ export default function Ractive$reset ( data, callback ) {
runloop.end();
}

this.fire( 'reset', data );
fireEvent( this, 'reset', { args: [ data ] });

if ( callback ) {
promise.then( callback );
Expand Down
58 changes: 58 additions & 0 deletions src/Ractive/prototype/shared/fireEvent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import getPotentialWildcardMatches from 'utils/getPotentialWildcardMatches';

export default function fireEvent ( ractive, eventName, options = {} ) {
if ( !eventName ) { return; }
var eventNames = getPotentialWildcardMatches( eventName );
fireEventAs( ractive, eventNames, options.event, options.args, true );
}

function fireEventAs ( ractive, eventNames, event, args, initialFire = false ) {

var subscribers, i, bubble = true;

for ( i = eventNames.length; i >= 0; i-- ) {
subscribers = ractive._subs[ eventNames[ i ] ];

if ( subscribers ) {
bubble = notifySubscribers( ractive, subscribers, event, args ) && bubble;
}
}

if ( ractive._parent && bubble ) {

if ( initialFire && ractive.component ) {
let fullName = ractive.component.name + '.' + eventNames[ eventNames.length-1 ];
eventNames = getPotentialWildcardMatches( fullName );

if( event ) {
event.component = ractive;
}
}

fireEventAs( ractive._parent, eventNames, event, args );
}
}

function notifySubscribers ( ractive, subscribers, event, args ) {

var originalEvent = null, stopEvent = false;

if ( event ) {
args = [ event ].concat( args );
}

for ( let i = 0, len = subscribers.length; i < len; i += 1 ) {
if ( subscribers[ i ].apply( ractive, args ) === false ) {
stopEvent = true;
}
}

if ( event && stopEvent && ( originalEvent = event.original ) ) {
originalEvent.preventDefault && originalEvent.preventDefault();
originalEvent.stopPropagation && originalEvent.stopPropagation();
}

return !stopEvent;
}


3 changes: 2 additions & 1 deletion src/Ractive/prototype/teardown.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import fireEvent from 'Ractive/prototype/shared/fireEvent';
import removeFromArray from 'utils/removeFromArray';
import Promise from 'utils/Promise';

Expand All @@ -7,7 +8,7 @@ import Promise from 'utils/Promise';
export default function Ractive$teardown ( callback ) {
var promise;

this.fire( 'teardown' );
fireEvent( this, 'teardown' );
this.fragment.unbind();
this.viewmodel.teardown();

Expand Down
3 changes: 2 additions & 1 deletion src/Ractive/prototype/update.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import fireEvent from 'Ractive/prototype/shared/fireEvent';
import runloop from 'global/runloop';

export default function Ractive$update ( keypath, callback ) {
Expand All @@ -15,7 +16,7 @@ export default function Ractive$update ( keypath, callback ) {
this.viewmodel.mark( keypath );
runloop.end();

this.fire( 'update', keypath );
fireEvent( this, 'update', { args: [ keypath ] });

if ( callback ) {
promise.then( callback.bind( this ) );
Expand Down
5 changes: 0 additions & 5 deletions src/config/defaults/options.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
// These are both the values for Ractive.defaults
// as well as the determination for whether an option
// value will be placed on Component.defaults
// (versus directly on Component) during an extend operation

var defaultOptions = {

// render placement:
Expand Down
5 changes: 4 additions & 1 deletion src/config/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,8 @@ export default {
'A function was specified for "{name}" {registry}, but no {registry} was returned',

defaultElSpecified:
'The <{name}/> component has a default `el` property; it has been disregarded'
'The <{name}/> component has a default `el` property; it has been disregarded',

noElementProxyEventWildcards:
'Only component proxy-events may contain "*" wildcards, <{element} on-{event}/> is not valid.'
};
3 changes: 2 additions & 1 deletion src/global/runloop.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import circular from 'circular';
import fireEvent from 'Ractive/prototype/shared/fireEvent';
import removeFromArray from 'utils/removeFromArray';
import Promise from 'utils/Promise';
import resolveRef from 'shared/resolveRef';
Expand Down Expand Up @@ -88,7 +89,7 @@ function flushChanges () {
changeHash = thing.applyChanges();

if ( changeHash ) {
thing.ractive.fire( 'change', changeHash );
fireEvent( thing.ractive, 'change', { args: [ changeHash ] });
}
}
batch.viewmodels.length = 0;
Expand Down
2 changes: 1 addition & 1 deletion src/parse/converters/element.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import processDirective from 'parse/converters/element/processDirective';
var tagNamePattern = /^[a-zA-Z]{1,}:?[a-zA-Z0-9\-]*/,
validTagNameFollower = /^[\s\n\/>]/,
onPattern = /^on/,
proxyEventPattern = /^on-([a-zA-Z$_][a-zA-Z$_0-9\-]+)$/,
proxyEventPattern = /^on-([a-zA-Z\\*\\.$_][a-zA-Z\\*\\.$_0-9\-]+)$/,
reservedEventNames = /^(?:change|reset|teardown|update)$/,
directives = { 'intro-outro': 't0', intro: 't1', outro: 't2', decorator: 'o' },
exclude = { exclude: true },
Expand Down
70 changes: 3 additions & 67 deletions src/shared/notifyPatternObservers.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
var lastKey = /[^\.]+$/,
starMaps = {};
import getPotentialWildcardMatches from 'utils/getPotentialWildcardMatches';

var lastKey = /[^\.]+$/;

// TODO split into two functions? i.e. one for the top-level call, one for the cascade
export default function notifyPatternObservers ( ractive, registeredKeypath, actualKeypath, isParentOfChangedKeypath, isTopLevelCall ) {
Expand Down Expand Up @@ -48,68 +49,3 @@ export default function notifyPatternObservers ( ractive, registeredKeypath, act
}
}

// This function takes a keypath such as 'foo.bar.baz', and returns
// all the variants of that keypath that include a wildcard in place
// of a key, such as 'foo.bar.*', 'foo.*.baz', 'foo.*.*' and so on.
// These are then checked against the dependants map (ractive.viewmodel.depsMap)
// to see if any pattern observers are downstream of one or more of
// these wildcard keypaths (e.g. 'foo.bar.*.status')
function getPotentialWildcardMatches ( keypath ) {
var keys, starMap, mapper, i, result, wildcardKeypath;

keys = keypath.split( '.' );
starMap = getStarMap( keys.length );

result = [];

mapper = function ( star, i ) {
return star ? '*' : keys[i];
};

i = starMap.length;
while ( i-- ) {
wildcardKeypath = starMap[i].map( mapper ).join( '.' );

if ( !result[ wildcardKeypath ] ) {
result.push( wildcardKeypath );
result[ wildcardKeypath ] = true;
}
}

return result;
}

// This function returns all the possible true/false combinations for
// a given number - e.g. for two, the possible combinations are
// [ true, true ], [ true, false ], [ false, true ], [ false, false ].
// It does so by getting all the binary values between 0 and e.g. 11
function getStarMap ( num ) {
var ones = '', max, binary, starMap, mapper, i;

if ( !starMaps[ num ] ) {
starMap = [];

while ( ones.length < num ) {
ones += 1;
}

max = parseInt( ones, 2 );

mapper = function ( digit ) {
return digit === '1';
};

for ( i = 0; i <= max; i += 1 ) {
binary = i.toString( 2 );
while ( binary.length < num ) {
binary = '0' + binary;
}

starMap[i] = Array.prototype.map.call( binary, mapper );
}

starMaps[ num ] = starMap;
}

return starMaps[ num ];
}
72 changes: 72 additions & 0 deletions src/utils/getPotentialWildcardMatches.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
var starMaps = {};

// This function takes a keypath such as 'foo.bar.baz', and returns
// all the variants of that keypath that include a wildcard in place
// of a key, such as 'foo.bar.*', 'foo.*.baz', 'foo.*.*' and so on.
// These are then checked against the dependants map (ractive.viewmodel.depsMap)
// to see if any pattern observers are downstream of one or more of
// these wildcard keypaths (e.g. 'foo.bar.*.status')
export function getPotentialWildcardMatches ( keypath ) {
var keys, starMap, mapper, i, result, wildcardKeypath;

keys = keypath.split( '.' );
if( !( starMap = starMaps[ keys.length ]) ) {
starMap = getStarMap( keys.length );
}

result = [];

mapper = function ( star, i ) {
return star ? '*' : keys[i];
};

i = starMap.length;
while ( i-- ) {
wildcardKeypath = starMap[i].map( mapper ).join( '.' );

if ( !result[ wildcardKeypath ] ) {
result.push( wildcardKeypath );
result[ wildcardKeypath ] = true;
}
}

return result;
}

// This function returns all the possible true/false combinations for
// a given number - e.g. for two, the possible combinations are
// [ true, true ], [ true, false ], [ false, true ], [ false, false ].
// It does so by getting all the binary values between 0 and e.g. 11
function getStarMap ( num ) {
var ones = '', max, binary, starMap, mapper, i;

if ( !starMaps[ num ] ) {
starMap = [];

while ( ones.length < num ) {
ones += 1;
}

max = parseInt( ones, 2 );

mapper = function ( digit ) {
return digit === '1';
};

for ( i = 0; i <= max; i += 1 ) {
binary = i.toString( 2 );
while ( binary.length < num ) {
binary = '0' + binary;
}

starMap[i] = Array.prototype.map.call( binary, mapper );
}

starMaps[ num ] = starMap;
}

return starMaps[ num ];
}



2 changes: 1 addition & 1 deletion src/virtualdom/Fragment/prototype/bubble.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export default function Fragment$bubble () {
this.dirtyValue = this.dirtyArgs = true;

if ( this.inited && this.owner.bubble ) {
if ( this.inited && typeof this.owner.bubble === 'function' ) {
this.owner.bubble();
}
}
32 changes: 27 additions & 5 deletions src/virtualdom/items/Component/initialise/propagateEvents.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import circular from 'circular';
import fireEvent from 'Ractive/prototype/shared/fireEvent';
import log from 'utils/log';

// TODO how should event arguments be handled? e.g.
Expand All @@ -6,7 +8,13 @@ import log from 'utils/log';
// when 'foo' fires on the child, but the 1,2,3 arguments
// will be lost

export default function ( component, eventsDescriptor ) {
var Fragment;

circular.push( function () {
Fragment = circular.Fragment;
});

export default function propagateEvents ( component, eventsDescriptor ) {
var eventName;

for ( eventName in eventsDescriptor ) {
Expand All @@ -19,17 +27,31 @@ export default function ( component, eventsDescriptor ) {
function propagateEvent ( childInstance, parentInstance, eventName, proxyEventName ) {

if ( typeof proxyEventName !== 'string' ) {

log.error({
debug: parentInstance.debug,
message: 'noComponentEventArguments'
});
}

childInstance.on( eventName, function () {
var args = Array.prototype.slice.call( arguments );
args.unshift( proxyEventName );
var options;

// semi-weak test, but what else? tag the event obj ._isEvent ?
if ( arguments[0].node ) {
options = {
event: Array.prototype.shift.call( arguments ),
args: arguments
};
}
else {
options = {
args: Array.prototype.slice.call( arguments )
};
}

fireEvent( parentInstance, proxyEventName, options );

parentInstance.fire.apply( parentInstance, args );
// cancel bubbling
return false;
});
}
4 changes: 3 additions & 1 deletion src/virtualdom/items/Component/prototype/unrender.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import fireEvent from 'Ractive/prototype/shared/fireEvent';

export default function Component$unrender ( shouldDestroy ) {
this.instance.fire( 'teardown' );
fireEvent( this.instance, 'teardown', { reserved: true });

this.shouldDestroy = shouldDestroy;
this.instance.unrender();
Expand Down
Loading