ko-typed

0.7.0 • Public • Published

ko-typed

ko-typed provides observable extensions for restricting and converting observable values based on type. Supports validation.

Build Status Coverage Status

Installation

Node

npm install ko-typed

Web

bower install ko-typed

Usage

node

var ko = require('ko-typed')(require('knockout'));
 
var typed = ko.observable().extend({ type: 'Undefined|Number' })
var convert = typed.extend({ convert: 'String' })

web (global)

<html>
    <head>
        <script type="text/javascript" src="knockout.js"></script> 
        <script type="text/javascript" src="ko-typed.applied.web.min.js"></script> 
    </head>
    <body>
        <script>
            var typed = ko.observable().extend({ type: 'Undefined|Number' })
            var convert = typed.extend({ convert: 'String' })
        </script> 
    </body>
</html>

web (amd)

require.config({
    paths: {
        "knockout": ...,
        "ko-typed": "ko-typed.applied.web.min.js"
    }
});
require(['knockout', 'ko-typed'], function (ko) {
    var typed = ko.observable().extend({ type: 'Undefined|Number' })
    var convert = typed.extend({ convert: 'String' })
});

API

extenders

ko extenders are used to wrap a given observable and provide a typed interface.

extenders-type

Create a computed observable which only accepts a specified list of types. Does not perform conversions.

Supports:

  • Generic types
  • Custom types
  • Overrides
Example
var base = ko.observable();
var typed = base.extend({ type: 'Undefined|String' });
 
typed(); // good. undefined is of a supported type.
typed(undefined); // good. undefined is of a supported type.
typed('string'); // good. 'string' is of a supported type.
 
base(10); typed(); // bad. 10 is not of a supported type.
typed(10); // bad. 10 is not of a supported type.

See examples/type for more examples. See test/coverage/type for detailed tests.

extenders-convert

Create a computed observable which converts to and from internal and external types.

Supports:

  • Type restriction
  • Custom conversions
  • Default conversions
  • Overrides
Example
var base = ko.observable();
var typed = base.extend({ type: 'Undefined|String' });
var converted = typed.extend({ convert: true });
 
converted('');
assert.strictEqual(base(), undefined);
converted(10);
assert.strictEqual(base(), '10');
converted('string');
assert.strictEqual(base(), 'string');
 
base(undefined);
assert.strictEqual(converted(), undefined);
base('10');
assert.strictEqual(converted(), '10');
base('string');
assert.strictEqual(converted(), 'string');

See examples/convert for more examples. See test/coverage/convert for detailed tests.

converters

Converters between all common types are provided where conversion is common and unambiguous.

Readme

Keywords

Package Sidebar

Install

npm i ko-typed

Weekly Downloads

3

Version

0.7.0

License

Apache-2.0

Last publish

Collaborators

  • whenderson