How to use jQuery widgets as Visto views

JQuery widgets cannot be directly used as Visto views. The simplest way to use them is by initializing them in the view's "code-behind":

export class SampleView extends VistoView<IVistoViewModel> {
	loaded() {
		this.getElement("#myDiv").accordion({ heightStyle: "content" }); 
	}
	...
}

However, if you want to use widgets like Visto views - with two-way bindings and for example in KnockoutJS foreach bindings and with translations - you have to implement a view wrapper around them. The following code shows an example of a view wrapper for the JQuery color picker Spectrum (http://bgrins.github.io/spectrum) (as TypeScript code):

views/ColorPicker.html

<input type="text" id="vId_picker" />

The view has two two-way parameters: "color" and "enable".

views/ColorPicker.ts (view "code-behind", generates "views/ColorPicker.js")

import visto = module("libs/visto");
export class ColorPicker extends VistoView<IVistoViewModel> {
	color: KnockoutObservable<string>;
	enable: KnockoutObservable<boolean>;
	
	initialize(parameters) {
		this.color = this.parameters.getObservable<string>("color");
		this.enable = this.parameters.getObservable<boolean>("enable", true);
		
		this.subscribe(this.color, color => {
			(<any>this.getElement("#picker")).spectrum("set", color);
		});

		this.subscribe(this.enable, enable => {
			(<any>this.getElement("#picker")).
				spectrum(enable ? "enable" : "disable");
		});
	}

	loaded() {
		(<any>this.getElement("#picker")).spectrum({
			showInput: true,
			showButtons: false,
			showInitial: true,
			disabled: !this.enable(), 
			color: this.color(), 
			change: (color) => { this.color(color.toHexString()); }
		});
	}
}

Usage:
selectedColor is an observable or regular property of the view model.

<span data-bind="view: { name: 'ColorPicker', color: selectedColor }"></span>

Last edited Jul 26, 2013 at 9:43 PM by rsuter, version 10

Comments

No comments yet.