Skip to content

Instantly share code, notes, and snippets.

@andrewk
Created July 30, 2014 04:38
Show Gist options
  • Save andrewk/08427dfde590a5e29fb9 to your computer and use it in GitHub Desktop.
Save andrewk/08427dfde590a5e29fb9 to your computer and use it in GitHub Desktop.
Handling attaching Flight components to DOM nodes in async-injected content
define(function(require) {
'use strict';
var defineComponent = require('flight/lib/component');
return defineComponent(ComponentRegistry);
function ComponentRegistry() {
this.components = [];
this.defaultAttrs({
'attachOn': 'uiAttachComponents',
'registerOn': 'uiRegisterComponent'
});
this.after('initialize', function() {
this.on(document, this.attr.attachOn, this.attachComponents.bind(this));
this.on(document, this.attr.registerOn, this.registerComponent.bind(this));
});
this.registerComponent = function(e, data) {
var params = data.params || {};
this.components.push(
{
// Component class variable
'component' : data.component,
// String alias for looking up component
'alias' : data.alias,
// CSS selector for nodes to attach component to
'selector' : data.selector,
// Optional component parameters for attachTo
'params' : params
}
);
};
this.attachComponents = function(e, data) {
if (data && data.alias) {
this.components
.filter(function(obj) {return obj.alias === data.alias;})
.forEach(this.attachRegisteredComponent.bind(this));
} else {
this.components.forEach(this.attachRegisteredComponent.bind(this));
}
};
this.attachRegisteredComponent = function(obj) {
obj.component.attachTo(obj.selector, obj.params);
};
}
});
define(function(require) {
'use strict';
var ComponentRegistry = require('component-ui/component-registry');
var Tag = require('component-ui/tag');
var AsyncForm = require('component-ui/async-form');
// register Tag component for async attach
$(document).trigger('uiRegisterComponent', {
'component': Tag,
'alias': 'tag',
'selector': '[data-tag]'
});
$(document).trigger('uiRegisterComponent', {
'component': AsyncForm,
'alias': 'ajaxform',
'selector': '[data-async-form]',
'params': {'submitEvent' : 'uiFormSubmitted' }
});
// Attach all registered components
$(document).trigger('uiAttachComponents');
// Alternatively, single components can be requested
$(document).trigger('uiAttachComponents', { 'alias': 'tag'});
});
/**
* Example of decoupled "subcomponents", triggering the `attachTo` call of a specific registered component to be run again
*/
define(function(require) {
'use strict';
var defineComponent = require('flight/lib/component');
return defineComponent(SomeComponent);
function SomeComponent() {
this.after('initialize', function() {
this.on(document, 'hasNewContent', this.injectContent.bind(this));
});
this.injectContent(e, data) {
this.$node.html(data.html);
this.trigger('uiAttachComponents', {'alias': 'ajaxform'});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment