tailieunhanh - Pro JavaScript Design Patterns 2008 phần 6

Trong ví dụ này, chúng ta hãy nói rằng bạn có được một dự án mới tại nơi làm việc. Ban đầu nó có vẻ đơn giản: tạo ra một hình thức có giá trị có thể được lưu, phục hồi, và xác nhận. Bất kỳ một nửa tỷ lệ phát triển web có thể được điều này, phải không? Việc nắm bắt được nội dung và số lượng các yếu tố trong hình thức hoàn toàn vô danh | CHAPTER 9 THE COMPOSITE PATTERN 127 Example Form Validation In this example let s say you get a new project at work. Initially it seems simple create a form whose values can be saved restored and validated. Any half-rate web developer could pull this off right The catch is that the contents and number of elements in the form are completely unknown and will change from one user to the next. Figure 9-2 shows a typical example. A validate function that is tightly coupled to specific form fields such as Name and Address won t work because you won t know at development time what fields to look for. This is a perfect job for the composite. Figure 9-2. Each user can potentially see a different form. First name 1 1 Last name Email address 1 1 Website Day phone 1 1 Evening phone 1 1 Mobile phone 1 1 Fa 1 1 First let s identify the elements of a form and label them as either a composite or a leaf see Figure 9-3 for the identification . The most basic building blocks of a form are the fields where the user enters data input select and textarea tags. Fieldset tags which group related fields together are one level up. The top level is the form itself. Figure 9-3. Identifying the basic form elements as composite or leaf 128 CHAPTER 9 THE COMPOSITE PATTERN Note A composite should have a HAS-A relationship with its children not an IS-A relationship. A form has fieldsets and fieldsets have fields. A field is not a subclass of a fieldset. Because all objects within a composite respond to the same interface it might be tempting to think of them in terms of superclasses and subclasses but this is not the case. A leaf will not inherit from its composite. The first task is to create a dynamic form and implement the operations save and validate. The actual fields within the form can change from user to user so you cannot have a single save or validate function that will work for everyone. You want the form to be modular so that it can be appended to at any point in the future without .

TỪ KHÓA LIÊN QUAN