Skip to content
TANG edited this page Dec 14, 2016 · 7 revisions

组件的复用

sugar 定义的组件都是一种组件“类”:

// 定义组件
var MyComponent = sugar.Component.extend({/**/});
typeof MyComponent // function

// 生成组件实例
var component = sugar.core.create('aaa', MyComponent);
typeof component // object

MyComponent 是一个构造函数,生成组件的过程就是将组件的构造函数实例化(相当于 new 操作),所以除原有模板布局外,任何定义的组件都是可复用的!因为只需要定义一个“组件类”,就可以生成 N 个功能完全相同且相互独立的组件实例。

例子

var ShowGreet = sugar.Component.extend({
	init: function (config) {
		this.Super('init', config, {
			class: 'show-text',
			view: 'hello world!'
		});
	}
});

// 生成 3 个组件实例(默认追加方式为 `appendChild` 也可指定为 `replace`)
sugar.core.create('show1', ShowGreet, {
	target: document.body
});

sugar.core.create('show2', ShowGreet, {
	target: document.body
});

sugar.core.create('show3', ShowGreet, {
	target: document.body
});
...
<body>
	<div class="show-text">
		hello world!
	</div>
	<div class="show-text">
		hello world!
	</div>
	<div class="show-text">
		hello world!
	</div>
</body>
...

组件的复用通常用在一些通用组件的开发,比如 RadioGroup, DatePicker 等,这种通用组件的共同点是可以解决一些功能相同的组件的复用,实现 DRY (don't repeat yourself),使用组件的时候只需要关心组件的数据的输入即可。


上一篇:组件的布局

下一篇:组件的继承

Clone this wiki locally