npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

knockout.register

v0.2.4

Published

Enhanced knockout component module

Downloads

46

Readme

knockout.register

knockout.register helps to register component in a simpler and more powerful way.

import eventMixin from './mixin/event';
import style from './btn.css';
import template form './btn.tpl';

export default {
    name: 'btn',
    props: {
        text: {
            type: ko.types.String,
            required: true
        },
        type: ko.types.oneOf(
            'button',
            'submit',
            'reset'
        )
    },
    mixin: [
        eventMixin
    ],
    methods: {
        onClick(vm, ev) {

            // 'trigger' mix from eventMixin
            this.trigger('click', vm);
        }
    },
    style,
    template
};

Usage

Install from NPM:

npm install knockout.register --save
<script src="knockout.3.4.0.js"></script>
<script src="node_modules/knockout.register/dest/knockout.register.js"></script>

Native Component Module

knockout.register named knockout original component module as Native Component Module.

Cite from knockout documentation:

ko.components.register('my-component', {
    viewModel: {
        createViewModel: function(params, componentInfo) {
            // - 'params' is an object whose key/value pairs are the parameters
            //   passed from the component binding or custom element
            // - 'componentInfo.element' is the element the component is being
            //   injected into. When createViewModel is called, the template has
            //   already been injected into this element, but isn't yet bound.
            // - 'componentInfo.templateNodes' is an array containing any DOM
            //   nodes that have been supplied to the component. See below.

            // Return the desired view model instance, e.g.:
            return new MyViewModel(params);
        }
    },
    template: ...
});

Standard Component Module

knockout.register creates a new component module and named it as Standard Component Module.

Options

name

  • type: String (required)

The name for component and custom element.HTML elements are case-insensitive, so when using component the name need to use their kebab-case equivalents(eg. my-component).

props

  • type: Object (default: null)

A prop is a custom attribute for passing information from parent components.A child component needs to explicity declare the props it expects to receive using this options.

export default {
    name: 'child',
    props: {
        text: ko.types.String
    }
};

Then we can pass a plain string to it like so:

<child text="hello"></child>

It is possible for a component to specify requirements for the props it is receiving.If a requirement is not met, the plugin will emit warnings.

<child text="1"></child>

When a prop validation fails, the plugin will produce a console warning(if using the development build).

The validator can be a custom function, native constructors or combination:

export default {
    props: {

        // basic validator
        optionalString: ko.types.String,
        optionalNumber: ko.types.Number,
        optionalBoolean: ko.types.Boolean,
        optionalFunction: ko.types.Function,
        optionalObject: ko.types.Object,
        optionalArray: ko.types.Array,
        optionalDate: ko.types.Date,
        optionalRegexp: ko.types.Regexp,
        optionalNode: ko.types.Node,
        optionalElement: ko.types.Element,
        optionalAny: ko.types.any,
        optionalUser: ko.types.instanceof(User),
        optionalEnum: ko.types.oneOf('button', 'submit', 'reset'),

        // basic validator with default
        optionalStringWithDefault: ko.types.string, // default: ''
        optionalNumberWithDefault: ko.types.number, // default: 0
        optionalBooleanWithDefault: ko.types.boolean, // default: false
        optionalObjectWithDefault: ko.types.object, // default: {}
        optionalArrayWithDefault: ko.types.array, // default: []
        optionalFunctionWithDefault: ko.types.function, // default: noop
        optionalDateWithDefault: ko.types.date, // default: new Date()
        optionalRegExpWithDefault: ko.types.regexp, // default: null
        optionalNodeWithDefault: ko.types.node, // default: null
        optionalElementWithDefault: ko.types.element, // default: null

        // combination validator
        optionalObjectWithShape: {
            optionalString: ko.types.String,
            optionalNumber: ko.types.Number,
            optionalBoolean: ko.types.Boolean
        },
        optionalArrayOfObjectsWithShape: ko.types.arrayOf(
            ko.types.shape({
                string: ko.types.String,
                number: ko.types.Number,
                boolean: ko.types.Boolea
            })
        ),
        optionalUnion: ko.types.oneOfType(
            ko.types.String,
            ko.types.Number,
            ko.types.Boolean
        ),

        // custom validator
        customProp(props, propName) => {
            if (/* ... */) {
                return true; // valid
            } else {
                return false // invalid
            }
        },

        // misc
        requiredString: {
            type: ko.types.String,
            required: true
        },
        stringWithDefaultValue: {
            type: ko.types.String,
            default: 'default string'
        }
    }
};

computed & pureComputed

Putting too much logic into your templates can make them bloated and hard to maintain.You should use a computed property.Why pure?

export default {
    name: 'component',
    props: {
        firstName: String,
        lastName: String
    },
    pureComputed: {
        fullName() {
            return `${this.firstName()} ${thie.lastName()}`;
        }
    }
};

mixins

  • type: Array (default: null)

A mixin is a methods collection reused in multiply components.The merge stratege is dead simple just copy methods from a mixin to methods option of target component.

It is possible for a mixin to do something before and after mixing.

export default {

    // before mixing
    preMix() {
        this; // => this keyword refer to view model
    },

    // after mixing
    postMix() {},

    // the methods will be copied
    on() {},
    off() {},
    trigger() {}
};

methods

  • type: Object (default: null)

Built-in lifecycle and custom methods.The this keyword refs to building view model in lifecycle methods and not enuse in custom methods.

export default {
    methods: {

        // vm created
        created() {
            this.text(); // => ''
            this.componentInfo.element; // => null
        },

        // template compiled and inserted into DOM
        ready() {
            this.text(); // => ''
            this.componentInfo.element; // => element
        },

        // dispose component and clean up
        dispose() {
            this._computedObservable.dispose();
            this._domElement = null;
            this._timeoutHander = null;
        },

        // custom method
        customMethod() {
            this; // => not ensure ref to view model all the time
        }
    }
};

style

  • type: String (default: '')

A <style/> tag which wraps the style string will be created and inserted to <head/>.

template

  • type: String (default: '<!-- empty template -->')

Knockout will emit error and halt application if template not specified.This plugin will use a HTML comment string to cheat in registering.

License

MIT © BinRui.Guan