Skip to content
This repository has been archived by the owner on Dec 9, 2021. It is now read-only.

codeBelt/StructureJS

Repository files navigation

StructureJS

A class based utility library for building modular and scalable web platform applications. Features opt-in classes and utilities which provide a solid foundation and toolset to build your next project.

Developers accustomed to ActionScript will immediately find themselves at home.

Documentation

Install

With Node.js:

$ npm install structure-js

With Bower:

$ bower install structurejs

IDE Snippets

Boilerplate

StructureJS Boilerplate (Babel - ES6)

StructureJS Boilerplate (TypeScript - ES6 Modules)

StructureJS Boilerplate (TypeScript - CommonJS Modules)

StructureJS Boilerplate (Browserify - ES5)

StructureJS Boilerplate (RequireJS - ES5)

Examples

Core Classes

DOMElement

All view classes will extend the DOMElement class. Here is an example how you would setup your main application class.

import FooView from './views/FooView';
import BarView from './views/BarView';
import ExampleView from './views/ExampleView';

class App extends DOMElement {

    _exampleView = null;

    constructor() {
        super()
    }

    create() {
        super.create();

        // single instance of a component
        const $exampleView = this.$element.find('#js-ExampleView');
        
		this._exampleView = new ExampleView($exampleView);
		this.addChild(this._exampleView);

		// multiple instances of a component
		this.createComponents([
			{ selector: '.js-FooView', component: FooView },
			{ selector: '.js-BarView', component: BarView }
		]);
    }

}

export default App;

To start the application you would use appendTo method on the main application class to attach it to the DOM. Only use appendTo once per application. After that you will use the addChild methed for child views like in the above example. Example of using appendTo:

const app = new App();
app.appendTo('body');

DOMElement provides helper methods and adds the following lifecycle to your class, these methods get called in this order:

  • create()
  • enable()
  • layout()
class ExampleView extends DOMElement {

    constructor($element) {
        super($element);
    }

    create() {
        super.create();
        // Create or setup child objects in this parent class.
    }

    enable() {
        if (this.isEnabled === true) { return; }
        // Add any event listeners and/or enable the child objects.
        super.enable();
    }

    disable() {
        if (this.isEnabled === false) { return; }
        // Remove any event listeners and/or disable the child objects.
        super.disable();
    }

    layout() {
        // Layout or update the objects in this parent class.
    }
    
    destroy() {
        this.disable();
        // Call destroy on any child objects.
        // This super method will also null out your properties for garbage collection.
        super.destroy();
    }

}

export default ExampleView;

Example DOMElement View

Read more about DOMElement

EventDispatcher

A base event bus class for managing prioritized queues of event listeners and dispatched events.

this.dispatchEvent('change');

// Send data object with the event:
this.dispatchEvent('change', { some: 'data' });

// Example with an event object
// (event type, bubbling set to true, cancelable set to true, and passing data)
let event = new BaseEvent(BaseEvent.CHANGE, true, true, { some: 'data' });
this.dispatchEvent(event);

// Dispatching an inline event object
this.dispatchEvent(new BaseEvent(BaseEvent.CHANGE));

Read more about EventDispatcher

Read more about BaseEvent

EventBroker

A pub/sub static class for dispatching and listening for events.

EventBroker.addEventListener('change', this._handlerMethod, this);

// Using a constant event type
EventBroker.addEventListener(BaseEvent.CHANGE, this._handlerMethod, this);

// Event passed to the method will always be a BaseEvent object.
_handlerMethod(event) {
     console.log(event);
}

Read more about EventBroker

Read more about BaseEvent

Router

A static class for managing route patterns for single page applications.

  • {required}
  • :optional:
  • * (all)
// A route listener with an event handler
Router.add('/games/{gameName}/:level:/', this._onRouteHandler, this);
Router.start();

// The above route would match the string below:
// '/games/asteroids/2/'

// The Call back receives a RouterEvent object.
_onRouteHandler(routerEvent) {
    console.log(routerEvent.params);
}

Example Router

Read more about Router

Read more about Route

Read more about RouteEvent

jQueryEventListener

Similar to the .on() & .off() jQuery methods, this plugin allows you to bind your function calls and assign them to a property on the class avoiding something like setupHandlers or bindAll methods.

  • eventType
  • delegation (optional)
  • eventHandler
  • scope
enable() {
    if (this.isEnabled === true) { return; }

    this.$element.addEventListener('click', this._onClickHandler, this);
    this.$element.addEventListener('click', 'button', this._onClickHandler, this); // event delegation

    super.enable();
}

disable() {
    if (this.isEnabled === false) { return; }

    this.$element.removeEventListener('click', this._onClickHandler, this);
    this.$element.removeEventListener('click', 'button', this._onClickHandler, this);

    super.disable();
}

_onClickHandler(event) {
    console.log('click', event);
}

Read more about jQueryEventListener

Release History

  • 2017-02-15 v0.15.4 BaseModel - remove logic that was cloning children BaseModel's.

  • 2017-02-08 v0.15.3 BaseModel - Wasn't really fixed. Now it is fixed. Fingers crossed!

  • 2017-02-08 v0.15.2 BaseModel - Fixed issue with arrays having the same data for every item in the array when instantiated directly on the property. Fixed issue with child models not actually being cloned into new objects when .clone() is called on the parent model.

  • 2017-01-19 v0.15.1 Add missing Interface *.d.ts files.

  • 2017-01-19 v0.15.0 Add *.d.ts files and update TypeScript compiler version.

  • 2016-12-27 v0.14.9 Fix TypeScript file issues.

  • 2016-12-16 v0.14.8 Util - Fix issue with deletePropertyFromObject.

  • 2016-12-15 v0.14.7 BaseModel - Add the ability to pass options in as a second parameter. Supports { expand: true } so nested base model class will be instantiated instead of nulled out.

  • 2016-11-18 v0.14.6 BaseModel - Fix issue with properties having a function as it data.

  • 2016-10-26 v0.14.5 ValidationUtil - Update isValidEmailAddress regex. BrowserUtil - fix issue with event listener name.

  • 2016-10-26 v0.14.4 MerchantUtil - Update getCreditCardProvider method to work with only a few numbers.

  • 2016-10-26 v0.14.3 LocalStorageService - add an in memory fallback if window.localStorage is not available.

  • 2016-10-06 v0.14.2 EventDispatcher - add printEventListeners method and now getEventListeners returns the object of event listeners.

  • 2016-09-26 v0.14.1 LocalStorageService - rename method names.

  • 2016-09-17 v0.14.0 StringUtil - added toQueryString. Router - remove _toQueryString and fix buildRoute to remove extra back slashes.

  • 2016-09-16 v0.13.3 StringUtil - fix toSentence issue with grouped numbers. LocalStorageService - Allow namespace to be set in the constructor and add removeItemsWithNamespace method.

  • 2016-08-26 v0.13.2 Fix Router class where on load it would not navigate to the proper history route.

  • 2016-08-26 v0.13.1 Fix npm index class path issues.

  • 2016-08-26 v0.13.0 Rename ApplicationCacheController to ApplicationCacheService and move to service directory. Rename LocalStorageController to LocalStorageService and move to service directory. Move Router to service directory.

  • 2016-08-20 v0.12.8 Router - Add Router to npm index file.

  • 2016-08-19 v0.12.7 Router - Add HTML History API to the Router Class.

  • 2016-07-13 v0.12.6 BaseModel - Fix EventDispatcher.dispatchEvent issue Needed to cache current listener objects to prevent the edge case were another listener is added during the dispatch loop.

  • 2016-06-24 v0.12.5 BaseModel - fix issue if object was passed in with messing property and the property was assigned a BaseModel class it would keep reference to the class. Now it sets it to null. Router - validate method to allow validation checks before the Router class triggers the next route. LocalStorageController - Add example comments.

  • 2016-05-17 v0.12.4 Remove break; to stop TypeScript warning in ApplicationCacheController.getStatus method. Fix issue with Router.buildRoute method putting '/' in front of '?'. Rename snippet extensions.

  • 2016-05-11 v0.12.3 Remove jquery import and make it global for the eventListener plugin.

  • 2016-05-11 v0.12.2 Allow passing of arguments to the layout method. Fix Router.getCurrentRoute being null right after callback.

  • 2016-04-23 v0.12.0 Deprecated Stage class and the appendTo method. Copied the appendTo method to the DOMElement class.

  • 2016-02-29 v0.11.1 Update Router.buildRoute to turn an object passed in to query string.

  • 2016-02-06 v0.11.0 Prevent Collection.add from allowing null and undefined. Remove onEnabled and onDisabled methods.

  • 2016-01-22 v0.10.5 Change examples and IDE snippets back to the show the enable and disable way rather than the onEnabled or onDisabled way.

  • 2016-01-19 v0.10.4 Add maxConnections to BulkLoader to set the maximum number of simultaneous connections.

  • 2016-01-06 v0.10.3 Add onEnabled and onDisabled methods. Removed enable and disable methods from Examples and IDE Snippets.

  • 2015-12-30 v0.10.2 Publishing to NPM https://www.npmjs.com/package/structure-js

  • 2015-12-30 v0.10.1 EventDispatcher - Fix currentTarget when event is bubbling. Update IDE Snippets.

  • 2015-12-21 v0.10.0 Change TypeScript from CommonJS to ES6 modules.

  • 2015-12-20 v0.9.3 Add third optional parameter to EventBroker so you can pass the scope of the object that dispatched the event. Update EventDispatcher to always update the currentTarget property. Add EventBroker.waitFor, EventBroker.waitForOnce, EventBroker.removeWaitFor. Collection.get() remove clamping if index is out of bounds.

  • 2015-12-05 v0.9.2 Allow a custom indicator with StringUtil.truncate(). Update ide-snippets. Made the start method private in NetworkMonitor.

  • 2015-11-25 v0.9.1 Add Router.getCurrentRoute, Add Util.unique, Fix BrowserUtil.getBrowser and make public. Update docs to ES6/Typescript. Rename all private and protected method to have an underscore in front.

  • 2015-10-24 v0.9.0 Remove unnecessary classes. DisplayObject - rename update to renderCanvas. Util - add applyMixins static method. Updated BulkLoader and created BulkLoaderEvent. Update interface files.

  • 2015-10-03 v0.8.0 Rename ValueObject to BaseModel and update all classes using it. Added addEventListenerOnce to EventDispatcher and EventBroker. Fixed Collection assign it a type in the constructor causes issues if data was already that type.

  • 2015-09-04 v0.7.9 Remove Util.getClassName, Util.getFunctionName and add Util.getName. Fix issue with getQualifiedClassName now working when code was uglified (Now need to have mangle set as false). Remove jQuery dependency from TemplateFactory. Change private methods and properties to protected.

  • 2015-08-22 v0.7.8 Fix issue with disable not being called when the destroy method is called on a DisplayObject. Add import for DisplayObjectContainer on CanvasElement. Allow ComponentFactory.create to be called multiple times with the same selector names and not overwrite active components. Update addClientSideId and add removeClientSideId. Add BulkLoader, ImageLoader ...

  • 2015-07-20 v0.7.7 Fixed ValueObject - Allow data passed in that is an array to get assigned to the property even if it is not of type of an array. Fix for phone number validation.

  • 2015-06-23 v0.7.6 DOMElement createComponents rename componentClass to component.

  • 2015-06-18 v0.7.5 Add groupBy method on Collection. Change ValidationUtil.isPostalCode to be case insensitive.

  • 2015-06-10 v0.7.4 Add pluck method to Collection. Move removeChild destroy functionality from DisplayObjectContainer to DOMElement.

  • 2015-05-26 v0.7.3 Corrects string replacement on getBreakpoint

  • 2015-05-21 v0.7.2 Add showHours flag to NumberUtil.convertToHHMMSS to display as 00:05:23 or 05:23

  • 2015-05-12 v0.7.1 DOMElement have createComponents return the list of children it created. Fix small bugs. Update comments. Add some unit tests.

  • 2015-04-26 v0.7.0 Breaking changes: Rename createChildren to create. Rename layoutChildren to layout. Create DisplayObject class and have DisplayObjectContainer extend it. Add Canvas specific classes. Rename namespace StructureTS to StructureJS in TypeScript files. Change namespace from structurejs to StructureJS in JavaScript classes. Rename folder src to js.

  • 2015-04-15 v0.6.17 Previous version before I started doing this release history.