Skip to content

Instantly share code, notes, and snippets.

@uberbruns
Last active February 25, 2018 12:05
Show Gist options
  • Save uberbruns/4c4fe28d4fb780be9d50a7e7023b073f to your computer and use it in GitHub Desktop.
Save uberbruns/4c4fe28d4fb780be9d50a7e7023b073f to your computer and use it in GitHub Desktop.
A minimal js "framework" for extending server rendered html with bits of javascript.
import $ from "./query"
class AppManager {
constructor(viewControllerClasses) {
this.viewControllerClasses = viewControllerClasses
this.assemble()
}
// Find html nodes for the registered view controller classes.
// When found instantiates the view controllers with the
// found html node
assemble() {
this.viewControllerClasses.forEach( (viewControllerClass) => {
let name = viewControllerClass.getName()
let view = $.viewControllers(name)[0]
if (view !== undefined) {
this[name] = new viewControllerClass(view)
}
})
}
}
export default AppManager
<div data-view-controller="example">
<button data-view="someButton">Test</button>
</div>
import App from "./app_manager"
import ExampleViewController from "./example_view_controller"
// Instantiate app
let app = new App([
ExampleViewController
])
import $ from "../query"
class ExampleViewController {
static getName() { return "example" }
constructor(view) {
this.view = view
this.setupView()
}
setupView() {
let someButton = $.views(this.view, "someButton")[0]
someButton.addEventListener("click", (event) => {
// ...
})
}
}
export default ExampleViewController
class QueryHelper {
// Finds html nodes acting as views
static views(parent, name) {
if (arguments.length > 1) {
return this._query(arguments[0], "view", arguments[1])
} else {
return this._query(document, "view", arguments[0])
}
}
// Finds html nodes acting as view controllers
static viewControllers(parent, name) {
if (arguments.length > 1) {
return this._query(arguments[0], "view-controller", arguments[1])
} else {
return this._query(document, "view-controller", arguments[0])
}
}
static _query(parent, key, value) {
return Array.from(parent.querySelectorAll("[data-" + key + "=\"" + value + "\"]"))
}
}
export default QueryHelper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment