Knockoutjs 的Components 是一种自定义的组件,它以一种强大、简介的方式将你自己的ui代码组织成一种单独的、可重用的模块,自定义的组件(Component)有以下特点:
ko.components.register('like-widget', { viewModel: function(params) { // Data: value is either null, 'like', or 'dislike' this.chosenValue = params.value; // Behaviors this.like = function() { this.chosenValue('like'); }.bind(this); this.dislike = function() { this.chosenValue('dislike'); }.bind(this); }, template: '<div class="like-or-dislike" data-bind="visible: !chosenValue()">\ <button data-bind="click: like">Like it</button>\ <button data-bind="click: dislike">Dislike it</button>\ </div>\ <div class="result" data-bind="visible: chosenValue">\ You <strong data-bind="text: chosenValue"></strong> it\ </div>' });通常情况下,你需要引入外部文件来加载viewModel和模板,而不是像上面这样写到同一个文件里。稍后我们讲解怎么以引入外部文件的方式加载viewModel和template。
<ul data-bind="foreach: products"> <li class="product"> <strong data-bind="text: name"></strong> <like-widget params="value: userRating"></like-widget> </li> </ul>
function Product(name, rating) { this.name = name; this.userRating = ko.observable(rating || null); } function MyViewModel() { this.products = [ new Product('Garlic bread'), new Product('Pain au chocolat'), new Product('Seagull spaghetti', 'like') // This one was already 'liked' ]; } ko.applyBindings(new MyViewModel());
ko.components.register('like-or-dislike', { viewModel: { require: 'files/component-like-widget' }, template: { require: 'text!files/component-like-widget.html' } });需要的文件:
files/component-like-widget.js
和
files/component-like-widget.html
。你是不是发现,这比直接在组件的定义里面包含viewModel和template要整洁、方便很多。
define(['knockout'], function(ko) { function LikeWidgetViewModel(params) { this.chosenValue = params.value; } LikeWidgetViewModel.prototype.like = function() { this.chosenValue('like'); }; LikeWidgetViewModel.prototype.dislike = function() { this.chosenValue('dislike'); }; return LikeWidgetViewModel; });files/component-like-widget.html code:
<div class="like-or-dislike" data-bind="visible: !chosenValue()"> <button data-bind="click: like">Like it</button> <button data-bind="click: dislike">Dislike it</button> </div> <div class="result" data-bind="visible: chosenValue"> You <strong data-bind="text: chosenValue"></strong> it. And this was loaded from an external file. </div>
下面是源码:
view :
<ul data-bind="foreach: products"> <li class="product"> <strong data-bind="text: name"></strong> <like-or-dislike params="value: userRating"></like-or-dislike> </li> </ul> <button data-bind="click: addProduct">Add a product</button>
function Product(name, rating) { this.name = name; this.userRating = ko.observable(rating || null); } function MyViewModel() { this.products = ko.observableArray(); // Start empty } MyViewModel.prototype.addProduct = function() { var name = 'Product ' + (this.products().length + 1); this.products.push(new Product(name)); }; ko.applyBindings(new MyViewModel());
Knockoutjs源出处:http://knockoutjs.com/documentation/component-overview.html