Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Inherit

TANG edited this page Dec 14, 2016 · 7 revisions

组件的继承

sugar.js 中,所有的视图组件都是通过继承 sugar.Component 来实现定义的:

var MyComponent = sugar.Component.extend({
	init: function (config) {
		this.Super('init', config, {
			// 在这里配置组件的参数
		});
	}
});

以上是定义一个视图组件最基本的"套路",关于组件继承有两个关键字是需要注意的:

1. extend

extend 是组件的继承方法,MyComponent 是继承于 sugar.Component 的组件,MyComponent 也拥有继承方法 extend ,所以 MyComponent 也可以作为一个基础组件类来继承出其他组件:

var MyComponent2 = MyComponent.extend({
	init: function (config) {
		this.Super('init', config);
	}
	// 在这里可以选择性的新增属性或方法去完成 MyComponent 以外功能需求
	// 同时 MyComponent 最初定义的方法和功能仍然存在,除非在这里被重写
	// 不管新增或者被重写与否,原来的 MyComponent 不受任何影响(immutable)
});
// 可以无限继承下去
var MyComponent3 = MyComponent2.extend({
	init: function (config) {
		this.Super('init', config);
	}
});
var MyComponent4 = MyComponent3.extend({
	init: function (config) {
		this.Super('init', config);
	}
});
// ...

2. Super

在组件内部 this.Super 的作用是调用指定父类的方法。以上在组件的 init 方法内调 this.Super('init', config) 的作用就是调用父类的 init 方法并传入组件配置,从而实现组件的渲染和构建,如果是多层继承关系也会进行逐层父类的调用,最终都会调用到 sugar.Componentinit 方法。

组件视图的渲染细节已经全部在 sugar.Componentinit 方法中去实现和完成,这就是为什么在定义组件的时候只需要简单的配置参数、定义初始状态和数据就可以实现一个完整的组件,而完全不必去关心组件构建细节的原因。


上一篇:组件的复用

下一篇:组件的嵌套

Clone this wiki locally

AltStyle によって変換されたページ (->オリジナル) /