knockoutjs : components

Components are a powerful, clean way of organizing your UI code into self-contained, reusable chunks. This feature allows developer to build some custom UI components that will have it’s own view and logic. You can register a component using ko.components.register (technically, registration is optional, but it’s the easiest way to get started). A component definition specifies a viewModel and template.

  • viewModel is optional
  • template is required

REGISTRATION

ko.components.register('mywidget', {
    viewModel: function(params) {
        //Define view model here
        this.title = ko.observable("I am a Widget");
    },
    template: '</pre>
<div></div>
<pre>'
});

USE


<mywidget></mywidget>

OR

</pre>
<div data-bind="component: {
     name: &quot;mywidget&quot;
}"></div>
<pre>

Example with Backbone


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Home Page</title>
<script type="text/javascript" src="../lib/knockout-3.2.0.debug.js"></script>
<script type="text/javascript" src="../lib/underscore.js"></script>
<script type="text/javascript"
	src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript"
	src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone-min.js"></script>
<script type="text/javascript" src="../js/demo.js"></script>
</head>
<body>
	<div id="start-div">
		<div id="title-div"></div>
		<div id="my-widget"></div>
	</div>
</body>
</html>

demo.js


$(document).ready(function() {
	var MyView = Backbone.View.extend({
		el : '#start-div',
		render : function() {
			this.$el.find("#title-div").html('Hello Knockout');
			this.koStart();
		},

		koStart : function() {
			this.initKOComponent();
			this.$el.find("#my-widget").append("<mywidget params='titleText: title'></mywidget>");
			
			var viewModel = {
					title : "I am a custom Widget"
				};
			
			ko.applyBindings(viewModel);
		},
		initKOComponent : function() {
			ko.components.register('mywidget', {
				viewModel : function(params) {
					this.widgetTitle = ko.observable(params.titleText);
				},
				template : '<div data-bind="text: widgetTitle"></div>'
			});
		}

	});
	var myView = new MyView();
	myView.render();

});

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s