corner-man

1.0.1 • Public • Published

CornerMan

Knockouts faithful servant.

Codeship Status for XLabKC/CornerMan

Example

function HelloVM() {
  CornerMan.ViewModel.call(this, 'hello-template');
  this.nameProvider = this.createChildObservable();
}
CornerMan.inherit(HelloVM, CornerMan.ViewModel);
   
function NameVM() {
  ViewModel.call(this, 'name-template');
  this.name = ko.observable('World');
}
CornerMan.inherit(NameVM, CornerMan.ViewModel);
 
var helloVM = new HelloVM();
var nameVM = new NameVM();
helloVM.nameProvider(nameVM);
 
var app = CornerMan.create();
app.setRootViewModel(helloVM);
app.bindRootViewModel();

Works with CoffeeScript class too:

class HelloVM extends CornerMan.ViewModel
  constructor: ->
    super('hello-template')
    @nameProvider = @childObservable()
 
class NameVM extends CornerMan.ViewModel
  constructor: ->
    super('name-template')
    @name = ko.observable('World')
 
helloVM = new HelloVM()
nameVM = new NameVM()
helloVM.nameProvider(nameVM)
 
app = CornerMan.create()
app.setRootViewModel(helloVM)
app.bindRootViewModel()

CornerMan API

The CornerMan API is exposed through the global variable CornerMan.

// Classes
CornerMan.Router            // Provides URL routing infastructure.
CornerMan.ViewModel         // Base ViewModel
CornerMan.ContentViewModel  // Subclass of ViewModel, provides propagated controls 
CornerMan.ControlViewModel  // Subclass of ViewModel, used with the ContentViewModel
CornerMan.Events            // Definition of events dispatched from ViewModel when changes occur
 
// Utils
CornerMan.inherit           // Helper for correctly setting up prototype chain when subclassing.
CornerMan.create            // Initializes a new CornerMan instance

CornerMan

The global CornerMan variable is also a class providing shortcuts for setting up the app.

CornerMan(rootViewModel)

  • rootViewModel ViewModel (optional): The root ViewModel of the application.

It's easiest to have a single root ViewModel that then has children for the various sections of the application.

function FooViewModel() {
  CornerMan.ViewModel.call(this, 'foo-template');
}
CornerMan.inherit(FooViewModel, CornerMan.ViewModel);
 
var rootViewModel = new FooViewModel();
var app = new CornerMan(rootViewModel) // or CornerMan.create(rootViewModel)
app.bindRootViewModel();

getRootViewModel()

  • => ViewModel: Returns the root ViewModel or null.

setRootViewModel(rootViewModel)

  • rootViewModel ViewModel

registerRoute(route, callback [, callback ]...)

  • route String: Route to register the callback(s) with.
  • callbacks Function: Functions called when the URL matches the given route.

Adds a route to the Router associated with this CornerMan instance. For more details, see Router#registerRoute below.

get(route, callback [, callback ]...)

  • route String: Route to register the callback(s) with.
  • callbacks Function: Functions called when the URL matches the given route.

Alas for #registerRoute.

listen()

Calls #listen on the Router associated with this CornerMan instance. For more details, see Router#listen below.

setTemplateEngine(templateEngine)

  • templateEngine ko.nativeTemplateEngine: Subclass of Knockout's template engine. Sets a template engine that will be used for all child and children data bindings.

bindRootViewModel(element)

  • element Node (optional): DOM element to bind the root ViewModel to.

Binds the root ViewModel to the given element or document.body if no element is given.

ViewModel API

ViewModel

CornerMan.ViewModel

ViewModel(template)

  • template String (optional): Template for the ViewModel.
function FooViewModel() {
  CornerMan.ViewModel.call(this, 'foo-template');
}
CornerMan.inherit(FooViewModel, CornerMan.ViewModel);

Events (CornerMan.Events)

CHILD_ADDED

Dispatched from a ViewModel when a child is added to it.

var viewModel = new ViewModel();
viewModel.addListener(CornerMan.Events.CHILD_ADDED, function(event, child, key) {
  //...
});
CHILD_MOVED

Dispatched from a ViewModel when a child is moved from one key to another.

var viewModel = new ViewModel();
viewModel.addListener(CornerMan.Events.CHILD_MOVED,
    function(event, child, oldKey, newKey) {
  //...
});
CHILD_REMOVED

Dispatched from a ViewModel when a child is removed from it.

var viewModel = new ViewModel();
viewModel.addListener(CornerMan.Events.CHILD_REMOVED, function(event, child, oldKey) {
  //...
});
MOVED_KEYS

Dispatched from a ViewModel when the ViewModel moves from one key to another key but without its parent changing.

var viewModel = new ViewModel();
viewModel.addListener(CornerMan.Events.MOVED_KEYS,
    function(event, parent, oldKey, newKey) {
  //...
});
ADDED_TO_PARENT

Dispatched from a ViewModel when the ViewModel is added as a child to another ViewModel.

var viewModel = new ViewModel();
viewModel.addListener(CornerMan.Events.ADDED_TO_PARENT, function(event, parent, key) {
  //...
});
REMOVED_FROM_PARENT

Dispatched from a ViewModel when the ViewModel is removed as a child from another ViewModel.

var viewModel = new ViewModel();
viewModel.addListener(CornerMan.Events.REMOVED_FROM_PARENT,
    function(event, parent, oldKey)
  //...
});

Methods

childObservation(initialValue, options)

  • initialValue ViewModel
  • options Object
    • key String (optional): The key to use for this observable
  • => Observable: Returns a Knockout observable

Creates an observable that contains a ViewModel. Any ViewModel set in the observable will be set as a child of this ViewModel.

function FooViewModel() {
  CornerMan.ViewModel.call(this);
  this.child = this.childObservable();
};
CornerMan.inherit(FooViewModel, CornerMan.ViewModel);

childrenObservable(initialValue, options)

  • initialValue ViewModel
  • options Object
    • key String (optional): The key to use for this observable
  • => Observable: Returns a Knockout observable

Creates an observable that contains an array of ViewModels. ViewModels added/removed from this observable be set as children of this observable.

function FooViewModel() {
  CornerMan.ViewModel.call(this);
  this.children = this.childrenObservable();
};
CornerMan.inherit(FooViewModel, CornerMan.ViewModel);
 
var fooVM = new FooViewModel();

addListener(event, callback)

  • event ViewModel.Events
  • callback Function: Refer to ViewModel.Events for callback parameters

Adds a listener to the ViewModel.

removeListener(listener)

  • listener Function: The callback function passed to #addListener

Removes the listener from the ViewModel.

getParent()

  • => ViewModel: Returns the parent of this ViewModel or null.

getTemplate()

  • => String: Returns the template of this ViewModel or null.

getKeys()

  • => Array< String >: Returns all of the child keys of this ViewModel.

getKeysObservable()

  • => Observable< Array< String > >: Returns an observable containing all of the child keys of this ViewModel.

getChildren()

  • => Array< ViewModel >: Returns all of the children of this ViewModel.

getChildrenObservable()

  • => Observable< Array< ViewModel > >: Returns an observable containing all of the children of this ViewModel.

getChildrenForKey(key)

  • key String
  • => Array< ViewModel >: Returns all of the children of this ViewModel at the given key.

getChildrenObservableForKey(key)

  • key String
  • => Observable< Array< ViewModel > >: Returns an observable containing all of the children of this ViewModel at the given key.

getKeyForChild(viewModel)

  • viewModel ViewModel: Child of this ViewModel
  • => String: The key of the given ViewModel or null.

addChildAtKey(key, viewModel)

  • key String
  • viewModel ViewModel: ViewModel to add as a child of this ViewModel.
  • => Boolean: Returns true if the ViewModel was added as a child at the given key; returns false if the ViewModel is already a child at the given key.

If the key is not significant, consider using #addChild instead.

addChildrenAtKey(key, viewModels)

  • key String
  • viewModels Array< ViewModel >: ViewModels to add as childlren of this ViewModel.

If the key is not significant, consider using #addChildren instead.

addChild(viewModel)

  • viewModel ViewModel: ViewModel to add as a child of this ViewModel.
  • => String: Returns the key generated for the new child.

To add a child with a given key, use #addChildAtKey instead.

addChildren(viewModel)

  • viewModel ViewModel: ViewModel to add as a child of this ViewModel.
  • => String: Returns the key generated for the new child.

To add childlren with a given key, use #addChildlrenAtKey instead.

removeChildAtKey(key, viewModel)

  • key String
  • viewModel ViewModel: Child ViewModel to remove.
  • => Boolean: Returns true if the child exists at the given key and was removed from this ViewModel; returns false otherwise.

removeChild(viewModel)

  • viewModel ViewModel: Child ViewModel to remove.
  • => Boolean: Returns true if the ViewModel is a child of this ViewModel and was removed; returns false otherwise.

replaceChildrenAtKey(key, viewModels)

  • key String
  • viewModels ViewModel: ViewModels to add as children of this ViewModel. Removes all child existing at the given key and then adds all of the given ViewModels at that key.

ViewModel.generateKey([length] [, availableCharacters])

  • length String (optional): Length of the key to generate, defaults to 10.
  • availableCharacters String (optional): String containing all of the available characters to use when generating the key. Defaults to alphanumeric.

Generates a key with the given length using the available characters.

ContentViewModel

CornerMan.ContentViewModel

ContentViewModel(template)

  • template String (optional): Template for the ContentViewModel.
function FooContentViewModel() {
  CornerMan.ContentViewModel.call(this, 'foo-template');
}
CornerMan.inherit(FooContentViewModel, CornerMan.ContentViewModel);
 
var fooVM = new FooContentViewModel();

getControlsForKey(key)

  • key String
  • => Array< ControlViewModel >: Returns the controls for the given key.

Gets the controls for the given key; any controls at the same key associated with children of this content ViewModel will be included. The controls are sorted by ascending using the order of the control ViewModel.

getControlsObservableForKey(key)

  • key String
  • => Observable< Array< ControlViewModel > >: Returns an observable containing the ControlViewModels for the given key.

Gets the observable that contains controls for the given key; any controls at the same key associated with children of this ContentViewModel will be included. The controls are sorted by ascending using the order of the ControlViewModel.

addControlAtKey(key, control)

  • key String
  • control ControlViewModel

Adds the given ControlViewModel to this ContentViewModel at the given key.

ControlViewModel

CornerMan.ControlViewModel

ControlViewModel(template, order)

  • template String (optional): Template for the ControlViewModel.
  • order Number: Order of the ControlViewModel.
function FooControlViewModel() {
  CornerMan.ControlViewModel.call(this, 'foo-template', 0);
}
CornerMan.inherit(FooControlViewModel, CornerMan.ControlViewModel);
 
var fooControl = new FooControlViewModel();

getOrder()

  • => Number: Returns the order of this ControlViewModel.

getOrder(order)

  • order Number

Set the order of this ControlViewModel.

Router API

Router

CornerMan.Router

Router(on404)

  • on404 Function (optional): Called when there is no registered route matching the current URL.
var router = new CornerMan.Router(function(url) {
  console.log('Unknown page:', url);
});

setOn404(on404)

  • on404 Function (optional): Called when there is no registered route matching the current URL.

Registers a function to be called when there is no registered route matching the current URL.

listen()

Starts the router listening for navigations. The current URL is immediately passed through the router.

registerRoute(route, callback [, callback ]...)

  • route String: Route to register the callback(s) with.
  • callbacks Function: Functions called when the URL matches the given route.

The router parameter can be a simple path, such as "/animals/dog" or it can contains "slugs" that match variable URLs such as "/animals/:animal". This second example will match any URL in the form of "/animals/..." but will not match "/animals/.../foo".

#registerRoute accepts a variable number of callbacks following the route parameter. The callbacks will be called in order with the following two parameters: request (Object) and next (Function). The request parameter has two properties: 1. params which contains the parameters parsed from the URL, and 2. query which contains the querystring parsed into an object. The next parameter is used to delegate to the next callback in the chain of registered callbacks. If a callback does not want of the following callbacks to be invoked, it simply shouldn't call next.

var router = CornerMan.Router();
 
router.registerRoute("/animals/:animal",
    function(request, next) {
      console.log('params', request.params);
      console.log('query', request.query);
      next();
    },
    function(request, next) {
      console.log('Handling URL.');
    },
    function(request, next) {
      console.log('Never called.');
    });
 
router.listen();
 
// User navigates to: /animals/dog?name=Max
 
// The following lines will be printed:
//   params { animal: 'dog' }
//   query { name: 'Max' }
//   Handling URL.

get(route, callback [, callback ]...)

  • route String: Route to register the callback(s) with.
  • callbacks Function: Functions called when the URL matches the given route.

Alias for #registerRoute.

navigate(url)

  • url String

Navigates to the given URL.

hasHistory()

  • => Returns whether there is a history entry to go back to.

This is useful to know if the user navigated to the current URL through the router, or if the user landed directly on the current URL, say through a link from an external site.

back()

Navigates back to the previous URL.

Package Sidebar

Install

npm i corner-man

Weekly Downloads

2

Version

1.0.1

License

MIT

Last publish

Collaborators

  • blakevanlan