DOC 15. [Concepts] How to use classes in Sencha Touch 2.0 (수정중) - KoreaSenchaUserGroup/Lab1 GitHub Wiki
DOC 15. [Concepts] How to use classes in Sencha Touch 2
원문 : http://docs.sencha.com/touch/2-0/#!/guide/class_system
번역 : 김태원 [Github:taewonkim]
편집 : 윤가희 [Github:5312559]
Watch the Class System video from SenchaCon 2011
Sencha Touch 2 uses the state of the art class system developed for Ext JS 4. It makes it easy to create new classes in JavaScript, providing inheritance, dependency loading, mixins, powerful configuration options, and lots more.
Sencha Touch 2 클래스 시스템은 ExtJS 4에서 개발된 시스템을 그대로 사용한다. 이 클래스 시스템은 자바스크립트에서 쉽게 새로운 클래스를 생성할 수 있게 쉽게 만들어 주며 상속, 의존성 로딩, mixins, 구성 옵션 외 많은 기능을 제공한다.
At its simplest, a class is just an object with some functions and properties attached to it. For instance, here's a class for an animal, recording its name and a function that makes it speak:
클래스 정의는 간단히 말해서 함수와 프로퍼티가 포함된 객체이다. 예를 들어, 자신의 이름이 있고, 소리를 낼 수 있는 동물 클래스는 다음과 같다.
Ext.define('Animal', {
config: {
name: null
},
constructor: function(config) {
this.initConfig(config);
},
speak: function() {
alert('grunt');
}
});
We now have a class called Animal
, where each animal can have a name and speak. To create a new instance of animal, we just use Ext.create:
위 클래스를 "Animal" 이라 부릅니다. 자신의 이름을 가지고, 소리를 낼 수 있는 동물 클래스를 구성해 보았습니다. 새로운 인스턴스를 생성하려면, Ext.create를 사용하시면 됩니다.
자신의 이름이 있고, 소리를 낼 수 있는 동물 클래스를 구성해 봤다. 동물 클래스의 새로운 인스턴스를 생성하려면, Ext.create를 사용하면 된다.
var bob = Ext.create('Animal', {
name: 'Bob'
});
bob.speak(); //alerts 'grunt'
Here we created an Animal called Bob and commanded it to speak. Now that we've created a class and instantiated it, we can start improving what we have. At the moment we don't know Bob's species, so let's clear that up with a Human
subclass:
이름이 ‘Bob’인 동물 인스턴스를 만들었고, speak 명령을 실행했다. 클래스를 생성하고, 인스턴스를 생성했으니, 우리가 원하는 대로 개선해 나갈 수 있다. 잠깐 Bob의 종에 대해 명확히 할 필요가 있다. Bob이 동물인지 사람인지 알 수 없으므로 Bob은 사람이라 가정하고, 동물 클래스를 확장해 Human 클래스를 만들어 보겠다. 사람도 동물이니깐요.
Ext.define('Human', {
extend: 'Animal',
speak: function() {
alert(this.getName());
}
});
Now we've got a new class that inherits from Animal, therefore gaining all of its functions and configurations. We actually overrode the speak function because most humans are smart enough to say their name instead of grunt. Now, let's make Bob a human:
동물 클래스를 상속해 새로운 클래스를 만들었다. 상위 클래스를 상속했으므로 상위 클래스의 모든 기능과 구성 정보를 받을 수 있다. 그러나 실제로 사람은 동물보다 영리하므로 꿀꿀거리며 말하는 대신 자신의 이름을 말 할 수 있다. 따라서 speak 메소드를 오버라이드해 자신의 이름을 말할 수 있게 재정의 했다. 이제 Bob 객체를 생성할 준비를 모두 끝마쳤으니 객체를 생성해보자.
var bob = Ext.create('Human', {
name: 'Bob'
});
bob.speak(); //alerts 'Bob'
We used a magical function when adding the Human subclass. You'll notice that we didn't actually define a getName function on our Animal class, so where did it come from? Part of the class system is the ability to give classes configuration options, which each automatically give you the following:
- a getter function that returns the current value, in this case
getName()
. - a setter function that sets a new value, in this case
setName()
. - an applier function called by the setter that lets you run a function when a configuration changes, in this case
applyName()
.
위의 코드에서 Human 서브클래스를 만들면서 마법과 같은 메소드를 사용하였습니다. Animal 클래스에서 getName 메소드를 선언하지 않았음에도 불구하고 호출하여 사용하고 있습니다. 이것은 대체 어디서 온 것일까요? 이것은 아래의 항목을 클래스 시스템에서 자동으로 제공되는 기능입니다.
- a getter function 은 현재 값을 리턴하고자 할 때 사용합니다. 이 경우에서는
getName()
과 같이 사용될 수 있습니다. - a setter function 은 새로운 값으로 변경하고자 할 때 사용합니다. 이 경우에서는
setName(new_value)
과 같이 사용될 수 있습니다. - applier function 은 setter에 의해 값을 변경할 때 호출되어집니다. 이 경우에는
applyName()
이며, 재정의 하여 값이 설정될 때 특별한 작업들을 할 수 있습니다.
The getter and setter functions are generated for free and are the recommended way to store data in a class. Every component in Sencha Touch uses the class system and the generated functions always follow the same pattern so if you know a config you already know how to get and set its value.
getter 및 setter 함수들은 클래스 프로퍼티에 데이터 저장하거나 읽어올 때, 사용하시면 좋습니다. Sencha Touch에 포함되어 있는 모든 컴포넌트, 클래스 시스템과 자동으로 생성되는 함수들 프로퍼티에 값을 저장하고 읽는 방법을 안다면, 항상 위의 항목과 동일한 패턴을 가지게 됩니다.
It also makes your code cleaner. For example, if you wanted to always ask the user if she really wants to change Bob's name, you can just define an applyName
function that will automatically be called:
getter과 setter를 사용하는 것은 깔끔하게 소스 코드를 유지할 수 있게 도와줍니다. 예를들어 “Bob”의 이름을 변경할 때, 사용자에게 항상 확인을 받아야 한다면, “applyName()” 함수를 정의하여 값을 할당할 때 자동으로 호출되도록 할 수도 있습니다.
Ext.define('Human', {
extend: 'Animal',
applyName: function(newName, oldName) {
return confirm('Are you sure you want to change name to ' + newName + '?')? newName : oldName;
}
});
We're just using the browser's built in confirm function, which opens a dialog asking the user the question and offering "Yes" and "No" as answers. The applier functions allow you to cancel the name change if you return false. As it happens the confirm function will return either new or old name depending on whether the user clicks Yes or No.
위 코드는 브라우저에 내장되어 있는 confirm 기능을 사용하여, 사용자가 “예”와 “아니오”를 선택할 수 있는 대화 상자를 출력할 수 있습니다. 위에서 작성한 “applier function”(여기서는 applyName() 메소드를 의미함.)에서 false를 반환한 경우에는, 진행하려고 하는 작업을(지금의 경우 이름 변경을 의미합니다.) 취소할 수도 있습니다. 여기서 confirm 기능을 통해 사용자가 선택한 “예” 또는 “아니오”에 따라 신규 또는 이전 이름을 반환할 것입니다.
If we make a new Bob and try to change his name, but then click No when prompted, his name won't change after all:
새로운 “Bob”를 만들고 그의 이름을 변경하려 시도하다가, 출력되는 프롬프트에서 “아니오” 선택지를 선택 하였다면, 그의 이름을 변경할 수 없을 것입니다.
var bob = Ext.create('Person', {
name: 'Bob'
});
bob.setName('Fred'); //opens a confirm box, but we click No
bob.speak(); //still alerts 'Bob'
We've basically already learned the important parts of classes, as follows:
- All classes are defined using
Ext.define
, including your own classes - Most classes extend other classes, using the
extend
syntax - Classes are created using
Ext.create
, for exampleExt.create('SomeClass', {some: 'configuration'})
- Always usine the
config
syntax to get automatic getters and setters and have a much cleaner codebase
지금까지 우리는 클래스의 중요한 것들을 배웠습니다. 아래의 항목에 정리해보도록 하겠습니다.
Ext.define
을 사용하여 여러분이 필요한 클래스를 만들 수 있습니다.- 다른 클래스로 부터 상속을 받기 원한다면
extend
syntax를 사용할 수 있습니다. - 인스턴스를 생성할 때는
Ext.create
를 사용하면 됩니다. 예를들면Ext.create('SomeClass', {some: 'configuration'})
와 같이 사용할 수 있습니다. - 항상
config
syntax는 getter과 setter을 자동으로 생성해주며, 코드를 깔금하게 만들어 줄 수 있습니다.
At this point you can already go about creating classes in your app, but the class system takes care of a few more things that will be helpful to lear are a few other things the class system does.
이 시점에서 응용프로그램 작성 하는데, 필요한 클래스를 직접 만드는 것이 가능합니다. 그러나 여러분이 클래스 시스템이 담당하는 도움이 될 만한 몇 가지 다른 것들도 있습니다.
Dependencies and Dynamic Loading
Most of the time, classes depend on other classes. The Human class above depends on the Animal class because it extends it - we depend on Animal being present to be able to define Human. Sometimes you'll make use of other classes inside a class, so you need to guarantee that those classes are on the page. Do this with the requires
syntax:
대부분의 클래스들은 다른 클래스들에 의존하여 실행됩니다. 위에서 작성한 Human 클래스는 Animal 클래스에서 확장되었습니다. --Human 클래스는 Animal에 의해 생성할 수 있습니다. 때때로 클래스 내에서 다른 클래스를 사용해야할 때가 있는데, 이때는 사용할 다른 클래스가 현재 작성하고 있는 클래스 범위에 존재한다는 것을 작성해야 합니다. 이러한 작업들을 requires
구문을 사용하여 해결할 수 있습니다.
Ext.define('Human', {
extend: 'Animal',
requires: 'Ext.MessageBox',
speak: function() {
Ext.Msg.alert(this.getName(), "Speaks...");
}
});
When you create a class in this way, Sencha Touch checks to see if Ext.MessageBox
is already loaded and if not, loads the required class file immediately with AJAX.
이 방법으로 클래스를 만들게 된다면, Sencha Touch 프레임워크에서 해당 모듈(여기서는 Ext.MessageBox
를 의미합니다.)이 로드되어 있는지, 아닌지를 체크하여 만약 로드 되지 않았다면 요구되는 클래스 파일을 AJAX를 사용하여 즉시 읽어들입니다.
Ext.MessageBox
itself may also have classes it depends on, which are then also loaded automatically in the background. Once all the required classes are loaded, the Human class is defined and you can start using Ext.create
to instantiate people. This works well in development mode as it means you don't have to manage the loading of all your scripts yourself, but not as well in production because loading files one by one over an internet connection is rather slow.
Ext.MessageBox
를 자세히 보시면 이 클래스의 어디에서도 해당 클래스 파일을 읽어오지 않습니다. 이 경우에는 백그라운드에서 자동으로 로드합니다. 일단 로드가 완료되면, Human
클래스는 선언되고 Ext.create
를 사용하여 people 객체를 사용할 수 있습니다. 개발시에는 자바스크립트 코드 파일들을 읽어 오는 것에 대해 지장이 없지만, 배포시에는 자바스크립트 코드 파일들을 인터넷 연결을 통해 읽어오는 것이 느리게 보일 것입니다.
In production, we really want to load just one JavaScript file, ideally containing only the classes that our application actually uses. This is really easy in Sencha Touch 2 using the JSBuilder tool, which analyzes your app and creates a single file build that contains all of your classes and only the framework classes your app actually uses. See the Building guide for details on how to use the JSBuilder.
배포 버전에서는 앱에서 실제로 사용하는 클래스들을 하나로 묶어 하나의 자바스크립트 파일만 로드하는 편이 좋을 수 있습니다. Sencha Touch 2에 포함되어 있는 JSBuilder 툴을 사용하는 것으로 간단하게 해결됩니다. 이 툴은 실제 앱 파일을 분석하여 사용자가 작성한 클래스들과 프레임워크에 포함되어 있는 클래스들 중 실제 사용된 자바스크립트 파일들을 포함하여 하나의 파일로 만듭니다. JSBuilder에 대해 더 자세히 알고 싶다면 Building guide를 참조하시면 됩니다.
Each approach has its own pros and cons, but can we have the good parts of both without the bad, too? The answer is yes, and we've implemented the solution in Sencha Touch 2.
각각의 방식에는 장단점이 있으나, 단점없이 장점만 가질 수 없나요? 예
. 이에 대한 해결법은 이미 Sencha Touch 2에서 구현되어 있습니다.
Naming Conventions
Using consistent naming conventions throughout your code base for classes, namespaces and filenames helps keep your code organized, structured, and readable.
명명규칙
을 사용하는 것은 클래스, 네임스페이스와 파일을 작성하는 동안 코드의 조직화, 구조화와 가독성을 높이는데 도움을 줄 수 있습니다.
1) Classes
Class names may only contain alphanumeric characters. Numbers are permitted but are discouraged in most cases, unless they belong to a technical term. Do not use underscores, hyphens, or any other nonalphanumeric character. For example:
MyCompany.useful_util.Debug_Toolbar
is discouragedMyCompany.util.Base64
is acceptable
클래스명은 영문, 숫자만 포함할 수 있습니다. 숫자까진 허용하지만, 대부분의 경우에는 영문, 숫자로 다 해결됩니다. 외에 다른 문자는 사용하지 마십시오. (언더스코어, 하이픈과 알파벳과 숫자를 제외한 문자.) 예를 들면 아래와 같습니다.
MyCompany.useful_util.Debug_Toolbar
허용되지 않는다.MyCompany.util.Base64
허용된다.
Class names should be grouped into packages where appropriate and properly namespaced using object property dot notation ( . ). At the minimum, there should be one unique top-level namespace followed by the class name. For example:
클래스는 네임스페이스로 점(dot notation)을 사용하여 그룹화하여 패키지로 구성할 수 있습니다. 이때, 최소한의 지켜져야 할 규칙은 최상위 네임스페이스명은 유일해야 하며 중복되면 안됩니다. 아래와 같이 작성할 수 있습니다.
MyCompany.data.CoolProxy
MyCompany.Application
The top-level namespaces and the actual class names should be in CamelCase, everything else should be all lower-cased. For example:
최상위 네임스페이스명과 클래스명을 작성할 때는 단어의 첫자는 대분자를 사용(CamelCase)하고 나머지는 소문자를 사용합니다. 아래와 같이 작성할 수 있습니다.
MyCompany.form.action.AutoLoad
Classes that are not distributed by Sencha should never use Ext
as the top-level namespace.
Sencha를 포함하여 배포할 때, 최상위 네임스페이스명에 Ext
를 포함하면 안됩니다.
Acronyms should also follow CamelCase convention, for example:
Ext.data.JsonProxy
instead ofExt.data.JSONProxy
MyCompany.util.HtmlParser
instead ofMyCompary.parser.HTMLParser
MyCompany.server.Http
instead ofMyCompany.server.HTTP
아래는 약어를 사용할 때 시작하는 단어의 첫글자를 대문자(CamelCase)로 사용하는 예를 보여주고 있습니다.
Ext.data.JSONProxy
대신에Ext.data.JsonProxy
MyCompary.parser.HTMLParser
대신에MyCompany.util.HtmlParser
MyCompany.server.HTTP
대신에MyCompany.server.Http
2) Source Files
The names of the classes map directly to the file paths in which they are stored. As a result, there must only be one class per file. For example:
Ext.mixin.Observable
is stored inpath/to/src/Ext/mixin/Observable.js
Ext.form.action.Submit
is stored inpath/to/src/Ext/form/action/Submit.js
MyCompany.chart.axis.Numeric
is stored inpath/to/src/MyCompany/chart/axis/Numeric.js
클래스 명은 저장되어 있는 파일 경로와 매핑되어 동작합니다. 결과적으로 하나의 클래스는 하나의 파일이라고 생각하시면 됩니다. 아래에 예를 보시면 이해가 더 쉬울 것입니다.
Ext.mixin.Observable
는path/to/src/Ext/mixin/Observable.js
에 저장되어 있습니다.Ext.form.action.Submit
는path/to/src/Ext/form/action/Submit.js
에 저장되어 있습니다.MyCompany.chart.axis.Numeric
는path/to/src/MyCompany/chart/axis/Numeric.js
에 저장되어 있습니다.
path/to/src
is the directory of your application's classes. All classes should stay under this common root and should be properly namespaced for the best development, maintenance, and deployment experience.
'path/to/src' 디렉토리는 어플리케이션 클랫들이 위치한 디렉토리를 의히마고 있습니다. 모든 클래스들을 루트 디렉토리와 네임스페이스가 지정하는 디렉토리에 위치할 수 있도록 배치하는 것이 개발, 관리, 배포에 도움을 줄 것입니다.
3) Methods and Variables
Similarly to class names, method and variable names may only contain alphanumeric characters. Numbers are permitted but are discouraged in most cases, unless they belong to a technical term. Do not use underscores, hyphens, or any other nonalphanumeric character.
클래스 이름과 비슷하게 모든 메소드와 변수이름을 지정할 때도 알파벳, 숫자만을 사용합니다. 숫자도 사용할 수 있으나 대부분의 경우에는 추천되지 않는 방법이다. 기술적으로 사용하지 못하는 것은 아닙니다. 언더스코어, 하이픈, 또는 알파벳이 아닌 문자는 사용할 수 없습니다.
Method and variable names should always use CamelCase. This also applies to acronyms.
메소드와 변수명은 시작한 단어의 첫글자에 대분자를 항상 사용하는 CamelCase를 사용합니다.
Here are a few examples:
아래의 목록에서 새로운 예를 보여주고 있습니다.
-
Acceptable method names:
encodeUsingMd5() getHtml() instead of getHTML() getJsonResponse() instead of getJSONResponse() parseXmlContent() instead of parseXMLContent()
-
허용되는 메소드 명:
encodeUsingMd5() getHTML() 대신에 getHtml() getJSONResponse() 대신에 getJsonResponse() parseXMLContent() 대신에 parseXmlContent()
-
Acceptable variable names:
-
허용되는 변수 명:
var isGoodName var base64Encoder var xmlReader var httpServer
4) Properties
Class property names follow the same convention as method and variable names, except the case when they are static constants. Static class properties that are constants should be all upper-cased, for example:
클래스 프로퍼티 이름은 일반적으로 메소드, 변수명과 같은 규칙을 사용합니다. 단, static
상수를 사용하고자 하는 경우를 제외됩니다. Static 클래스 프로퍼티는 대분자를 사용합니다. 아래에서 Static 클래스 프로퍼티의 예를 볼 수 있습니다.
Ext.MessageBox.YES = "Yes"
Ext.MessageBox.NO = "No"
MyCompany.alien.Math.PI = "4.13"
Working with classes in Sencha Touch 2.0
1. Declaration
1.1. The Old Way
If you've developed with Sencha Touch 1.x, you are certainly familiar with Ext.extend
to create a class:
만약 Sencha Touch 1.x 버전으로 개발해본 경험이 있다면, 클래스를 만들 때, Ext.extend
를 사용하는 것이 더 익숙할 것입니다.
var MyPanel = Ext.extend(Object, { ... });
This approach is easy to follow when creating a new class that inherits from another. Other than direct inheritance, however, there wasn't a fluent API for other aspects of class creation, such as configuration, statics, and mixins. We will be reviewing these items in detail shortly.
위의 예와 같은 경우 상속된 새로운 클래스를 만들 때 쉽게 만들어줍니다. 상속 이외에 다른 경우 즉, configuration, static 그리고 mixins과 같은 클래스를 생성하는 관점에서는 자유롭지 않습니다. 다시 자세히 한번 살펴보도록 하겠습니다.
Let's take a look at another example:
다른 예제를 봅시다.
My.cool.Panel = Ext.extend(Ext.Panel, { ... });
In this example we want to namespace our new class and make it extend from Ext.Panel
. There are two concerns we need to address:
My.cool
needs to be an existing object before we can assignPanel
as its property.Ext.Panel
needs to exist/be loaded on the page before it can be referenced.
이 예제에서 하려고 하는 것은 Ext.Panel
에서 상속받아 새로운 클래스를 만드는 것입니다. 여기서 관심있게 봐야할 사항이 2가지가 있습니다.
My.cool
은Panel
오브젝트가 있어야 한다.Ext.Panel
은 참조되기 전에 현재 영역에서 로드가 되어야 한다.
The first item is usually solved with Ext.namespace
(aliased by Ext.ns
). This method recursively traverses through the object/property tree and creates them if they don't exist yet. The boring part is you need to remember adding them above Ext.extend
all the time, like this:
첫번째 항목은 Ext.namespace
(Ext.ns
로 Alias되어 있습니다.)를 사용하는 것으로 해결할 수 있습니다. 이 메소드는 객체/프로퍼티가 존재하지 않을 경우 재귀적으로 객체/프로퍼티 트리를 검색 한 후 만들어집니다. 아래의 예와 같이 Ext.extend
를 붙이는 지루한 작업이 필요할수도 있습니다.
Ext.ns('My.cool');
My.cool.Panel = Ext.extend(Ext.Panel, { ... });
The second issue, however, is not easy to address because Ext.Panel
might depend on many other classes that it directly/indirectly inherits from, and in turn, these dependencies might depend on other classes to exist. For that reason, applications written before Sencha Touch 2 usually include the whole library in the form of ext-all.js
even though they might only need a small portion of the framework.
두번째 이슈는, 그닥 쉽지는 않습니다. Ext.Panel
은 수많은 클래스에 직/간접적으로 의존하고 있기 때문인데, 결국에는 Ext.Panel
클래스가 생성되기 위해 필요한 다른 클래스가 생성되어 있어야 한다는 의미를 가지고 있습니다. 이러한 이유로 Sencha Touch 2로 어플리케이션을 작성할 때는 필요한 항목이 몇 개 되지 않더라도 보통은 ext-all.js
를 포함하여 작성합니다.
1.2. The New Way
Sencha Touch 2 eliminates all those drawbacks with just one single method you need to remember for class creation: Ext.define
. Its basic syntax is as follows:
Sencha Touch 2 이전 버전의 단점을 모두 제거하였습니다. 단지 Ext.define
만 기억하는 것으로 클래스 생성에 모든 것을 해결할 수 있습니다. 기본 문법은 아래와 같습니다.
Ext.define(className, members, onClassCreated);
Let's look at each part of this:
className
is the class namemembers
is an object represents a collection of class members in key-value pairsonClassCreated
is an optional function callback to be invoked when all dependencies of this class are ready, and the class itself is fully created. Due to the new asynchronous nature of class creation, this callback can be useful in many situations. These will be discussed further in Section IV.
그럼, 각각의 파트에 대해 자세히 알아보겠습니다.
className
는 클래스명입니다.members
는 key와 value 짝으로 구성되며, 객체에 존재하는 클래스 멤버들입니다.onClassCreated
는 모든 파일이 로드되고, 클래스 생성이 준비 되었을 때 프레임워크에서 호출되는 콜백 함수입니다. 클래스가 생성되는 동안 이 콜백함수를 등록하면 좀 더 다양한 작업들을 할 수 있습니다. 이 부분에 대한 자세한 내용은 "섹션 4"에서 다룰 예정입니다.
Example
Ext.define('My.sample.Person', {
name: 'Unknown',
constructor: function(name) {
if (name) {
this.name = name;
}
},
eat: function(foodType) {
alert(this.name + " is eating: " + foodType);
}
});
var aaron = Ext.create('My.sample.Person', 'Aaron');
aaron.eat("Salad"); // alert("Aaron is eating: Salad");
Note we created a new instance of My.sample.Person
using the Ext.create()
method. We could have used the new
keyword (new My.sample.Person()
). However it is recommended that you always use Ext.create
since it allows you to take advantage of dynamic loading. For more info on dynamic loading see the Getting Started guide
노트 Ext.create
메소드를 사용하여 'My.sample.Person' 의 새로운 인스턴스를 만들었습니다. 이것은 자바스크립트에서 제공하는 new
키워드를 사용할 수 있었으나, (new My.sample.Person()
) 인스턴스를 만들 때는 ExtJS 클래스 시스템에서 제공하는 여러가지 장점을 살리기 위해서는 Ext.create
메소드를 사용하는 것을 권장합니다.
2. Configuration
In Sencha Touch 2, we introduce a dedicated config
property that is processed by the powerful Ext.Class
preprocessors before the class is created. Features include:
- Configurations are completely encapsulated from other class members.
- Getter and setter, methods for every config property are automatically generated into the class prototype during class creation if the class does not have these methods already defined.
- An
apply
method is also generated for every config property. The auto-generated setter method calls theapply
method internally before setting the value. Override theapply
method for a config property if you need to run custom logic before setting the value. Ifapply
does not return a value then the setter will not set the value. For an example seeapplyTitle
below.
Sencha Touch 2에서 혁신적인 config
프로퍼티를 소개하였고, 이는 클래스가 Ext.Class
프리프로세서로 부터 생성되기 이전에 실행됩니다. 다음과 같은 특징들을 포함하고 있습니다.
- Configuration(
config
) 프로퍼티는 다른 클래스 맴버로부터 완전 캡슐화 되어 있습니다. config
프로퍼티에 포함되어 있는 모든 구성 옵션들은 클래스가 생성되는 동안에 Getter와 setter와 같은 메소드들을 자동으로 생성(메소드를 따로 작성하지 않아도, 생성되어 있습니다.)해 줍니다.config
프로퍼티에 포함되어 있는 모든 프로퍼티에 대해apply
메소드를 생성합니다. 이를 auto-generated Setter 메소드라 부르며 내부적으로 값을 할당할 때 사용됩니다. 또한apply
메소드는 값을 할당하기 전에 무엇인가 하고 싶다면config
프로퍼티 내에서 재정의할 수 있습니다.apply
메소드를 작성할 때 반드시 값을 return 해야 합니다. 만약 하지 않는다면, setter 은 해당 변수에 값을 할당하지 않을 것입니다. 아래에applyTitle
를 작성하는 예를 보겠습니다.
Here's an example:
예제를 보겠습니다.
Ext.define('My.own.WindowBottomBar', {});
Ext.define('My.own.Window', {
/** @readonly */
isWindow: true,
config: {
title: 'Title Here',
bottomBar: {
enabled: true,
height: 50,
resizable: false
}
},
constructor: function(config) {
this.initConfig(config);
},
applyTitle: function(title) {
if (!Ext.isString(title) || title.length === 0) {
console.log('Error: Title must be a valid non-empty string');
}
else {
return title;
}
},
applyBottomBar: function(bottomBar) {
if (bottomBar && bottomBar.enabled) {
if (!this.bottomBar) {
return Ext.create('My.own.WindowBottomBar', bottomBar);
}
else {
this.bottomBar.setConfig(bottomBar);
}
}
}
});
And here's an example of how it can be used:
아래에 어떻게 사용되는지 예제를 볼 수 있습니다.
var myWindow = Ext.create('My.own.Window', {
title: 'Hello World',
bottomBar: {
height: 60
}
});
console.log(myWindow.getTitle()); // logs "Hello World"
myWindow.setTitle('Something New');
console.log(myWindow.getTitle()); // logs "Something New"
myWindow.setTitle(null); // logs "Error: Title must be a valid non-empty string"
myWindow.setBottomBar({ height: 100 }); // Bottom bar's height is changed to 100
3. Statics
Static members can be defined using the statics
config, as follows:
아래의 코드에서 보시는 바와 같이, Static 맴버 또한 “statics” config를 사용하여 정의할 수 있습니다.
Ext.define('Computer', {
statics: {
instanceCount: 0,
factory: function(brand) {
// 'this' in static methods refer to the class itself
return new this({brand: brand});
}
},
config: {
brand: null
},
constructor: function(config) {
this.initConfig(config);
// the 'self' property of an instance refers to its class
this.self.instanceCount ++;
}
});
var dellComputer = Computer.factory('Dell');
var appleComputer = Computer.factory('Mac');
alert(appleComputer.getBrand()); // using the auto-generated getter to get the value of a config property. Alerts "Mac"
alert(Computer.instanceCount); // Alerts "2"
Error Handling and debugging
Sencha Touch 2 includes some useful features that will help you with debugging and error handling.
Sencha Touch 2에는 디버깅과 에러 처리에 도움을 줄 수 있는 유용한 기능들이 부분적으로 포함되어 있습니다.
You can use Ext.getDisplayName()
to get the display name of any method. This is especially useful for throwing errors that have the class name and method name in their description, such as:
어떤한 메소드에서든지 메소드의 이름을 출력하기 위해서 Ext.getDisplayName()
메소드를 사용할 수 있습니다. 이 메소드는 예외가 발생했을 때 클래스 이름과 메소드 이름과 같은 정보들을 포함하고 있는 특별한 메소드입니다. 사용할 때는 아래와 같이 사용할 수 있습니다.
throw new Error('['+ Ext.getDisplayName(arguments.callee) +'] Some message here');
When an error is thrown in any method of any class defined using Ext.define()
, you should see the method and class names in the call stack if you are using a WebKit based browser (Chrome or Safari). For example, here is what it would look like in Chrome:
Ext.define()
를 사용하여 정의된 어떤 클래스, 메소드에서 에러가 발생했을 때, WebKit 기반 브라우저(크롬 또는 사파리)를 사용 하신다면, 콜스택에서 클래스와 메소드의 이름들을 확인할 수 있습니다. 아래의 그림에 크롬에서 예외가 던져졌을 때의 상황을 보실 수 있습니다.
Further Reading
Classes are just part of the Sencha Touch 2 ecosystem. To understand more about the framework and how it works, we recommend the following:
클래스 시스템은 Sencha Touch 2 프레임워크의 생태계의 일부분입니다. 이 외에도 프레임워크와 이를 활용하는 방법에 대해 좀 더 자세히 알고 싶다면 아래의 글을 읽어보는 것을 권장합니다.