0.0.1 • Published 5 years ago

knockout.bootstrapper v0.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
5 years ago

knockout.bootstrapper

A knockout structure for creating modern applications

This project was born to provide a quick structure to build better Multi Page Applications with KnockoutJs. I took inspiration from StimulusJs and applied a similar concept to Knockout.

If you like Multi Page Applications, Progressive Enhancement and was a JQuery fan back in the day, you will notice that you can easily use this strategy to bring life to your server rendered pages.

TODO:

  • Tests (Jasmine/ Karma)
  • Publish to NPM

Traditional view model usage:

The application will call ko.applyBindings to the root element when the DOM is ready. This allows us to use view models and components side-by-side anywhere on the body scope without worrying about binding it explicitly with Knockout. There's also a nice custom viewModel binding that allows you to specify the scocpe of your view models without having to binding them manually for each page.

Index.html:

<div data-bind:"viewModel: 'helloViewModel'">
  <input data-bind="text: name"></span>
  <button data-bind="click: say">Click Me!</button>
</div>

You can also use the following notation to pass initialization data to your view model:
data-bind:"viewModel: { name: 'helloViewModel', params: 'type your name' }"

helloViewModel.ts:

// Declare your Knockout ViewModel
class HelloViewModel extends ViewModel {
  public name: ko.Observable<string>;
  
  constructor(params: string){
    this.name = ko.observable<string>(params || '');
  }
    
  public say(): void {
    alert(this.name());
  }
}

application.ts:

const application = new Application();
application.registerViewModel("helloViewModel", HelloViewModel);
application.start();

Component usage:

/components/hello-world/index.ts:

import template from './index.html';
import './index.scss';

// You can reuse an existing view model or create one specific for this component.
// DON'T use this class as your view model, it is only a definition that 
// holds information about the template and view model to be used
class HelloComponent extends Component {
  constructor(name: string, viewModel: ViewModelClass) {
    super(name, viewModel, template)
  }
}

You can place a global.d.ts file in your /components folder with: declare module '*.html' so you can import your template files with typescript.
You also need to use some kind of html loader to include your component templates in your final bundle, which is trivial with Webpack:
module: { rules: [ { test: /\.html$/, loaders: ['html-loader'] } ] }.

/components/hello-world/index.html:

<div>
  <input data-bind="text: name"></span>
  <button data-bind="click: say">Click Me!</button>
</div>

application.ts:

const application = new Application();
application.registerComponent("hello-world", HelloComponent, HelloViewModel);
application.start();
0.0.1

5 years ago