Skip to content

WHenderson/ko-typed

Repository files navigation

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

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

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.

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 between all common types are provided where conversion is common and unambiguous.

About

KnockoutJs Type Restricted Observables

Resources

License

Stars

Watchers

Forks

Packages

No packages published