Skip to content

skyh/knockout-promise-extender

Repository files navigation

Knockout promise extender Build Status

Knockout extender for handling promises.

Installation

npm install knockout-promise-extender

Adding to knockout

var ko = require('knockout');
var promiseExtenderFactory = require('knockout-promise-extender');
ko.extenders.promise = promiseExtenderFactory(ko);

Usage

var x = ko.observable().extend({promise: true});

console.log(
    x, // observable
    x() // PromiseState
);

console.log(
    x().pending, // true
    x().resolved, // false
    x().rejected, // false
    x().value // undefined
);

x(Promise.resolve('some value'));

console.log(
    x().pending, // true, because Promise.resolve is async
    x().resolved, // false
    x().rejected, // false
    x().value // undefined
);

setTimeout(function () {
    console.log(
        x().pending, // false
        x().resolved, // true
        x().rejected, // false
        x().value // "some value"
    );
}, 0);

Usage in bindings

<div class="promised-model-view">
    <!-- ko if: x().pending -->
        <span class="wait-message">
            Loading data...
        </span>
    <!-- /ko -->

    <!-- ko if: x().resolved -->
        <span class="data" data-bind="text: x().value"></span>
    <!-- /ko -->

    <!-- ko if: x().rejected -->
        <span class="error-message">
            Something went wrong. Error is
            <span data-bind="text: x().value"></span>
        </span>
    <!-- /ko -->
</div>

About

Knockout extender for handling Promise instances

Resources

Stars

Watchers

Forks

Packages

No packages published