Meta-programming using JAVASCRIPT (Web site cannot be played)

Source: Internet
Author: User
Tags apple video

Felix Woo World because I exist
    • Home
    • Thinkpage
    • News
    • Weather
    • Glickr
    • Album
    • Message boards
    • Friendship Link
2007-88 Meta Programming with JavaScript posted: 16:50 | Category: Development Technology | Comments: 2 | Popularity: 279 |

Transferred from: Http://benchwang.spaces.live.com/blog/cns!1621B5CAD6EB680B!149.entry

Adam McCrea wrote a meta-programming article using javascript: metaprogamming JavaScript.
This article uses an example to illustrate meta-programming. The example is simple, a Form package in the two drop-down list country and state, the business requirement is the country drop-down list, select "a states" to display the list of countries, otherwise hide the drop-down list. The code that handles the logic is as follows:

Event.observe (window, "Load", function () {
Event.observe ($ ("Country"), "Change", function () {
if ($F ("country") = = "states")
$ ("State-field"). Show ();
Else
$ ("State-field"). Hide ();
});
});

The objects and methods used here are Prototype extensions to JavaScript. Prototype is a JavaScript Framework designed to simplify the development of dynamic WEB programs. See http://www.prototypejs.org/. In the above code: Event.observe is equivalent to attachevent in IE, which is used to register the event handler function. This is registered with the Window.onload and Country.onchange event handlers. $ () is an alias for document.getElementById (). $F () takes out the current value of the element in the form. Show () and hide () are methods that are added on HTML elements. Many methods are extended by prototype on the basis of HTML elements. If you want to run the above code, you need to download prototype.js and place it in the same directory as the HTML page. The complete code is as follows:

<title>metaprogramming Javascript-example 1</title>
<script src= "Prototype.js" ></script>
<script type= "Text/javascript" charset= "utf-8″>
Event.observe (window, "Load", function () {
Event.observe ($ ("Country"), "Change", function () {
if ($F ("country") = = "states")
$ ("State-field"). Show ();
Else
$ ("State-field"). Hide ();
});

});
</script>

<body>
<form>
<p id= "Country-field" >
<label for= "Country" >Country</label>
<select id= "Country" >
<option>united states</option>
<option>Canada</option>
<option>somewhere else</option>
</select>
</p>

<p id= "State-field" >
<label for= "state" >State</label>
<select id= "State" >
<option>Ohio</option>
<option>Michigan</option>
<option>Kentucky</option>
</select>
</p>
</form>
</body>

There is nothing wrong with the code to meet such simple needs. However, as demand changes, the code becomes cumbersome. If the following requirements are added:
Add Province Field
When country is "Canada", Display province
When country is "states", display state
When state is "Ohio" or "Michigen", display Brutus (very cute logo)
Based on the above requirements, the code is modified to:

Event.observe (window, "Load", function () {
Event.observe ($ ("Country"), "Change", function () {
var country = $F ("Country");
if (country = = "states") {
$ ("Us-state-field"). Show ();
$ ("Province-field"). Hide ();
} else if (country = = "Canada") {
$ ("Province-field"). Show ();
$ ("Us-state-field"). Hide ();
} else {
$ ("Us-state-field"). Hide ();
$ ("Province-field"). Hide ();
}
});

Event.observe ($ ("us-state"), "Change", function () {
var state = $F ("Us-state");
if (state = = "Ohio" | | state = = "Michigan")
$ ("Brutus"). Show ();
Else
$ ("Brutus"). Hide ();
});

});

The new program uses the previous event handling and field check methods to try to extend the program to meet the new requirements. However there are a few questions, the first question this code has two bug:1) when the page is initially loaded all fields are displayed, 2) Hiding the State field does not, and does not automatically hide the Brutus. The latter can be called a domino bug because if there are other elements that depend on the dynamic display and the hidden fields can cause cascading effects.

The second problem is the readability of the code. It is not easy to immediately see what this code wants to achieve, so it needs to be carefully checked for omission or not being strictly in line with the requirements. When requirements change, it is desirable to know exactly where the code needs to be modified and, as a modification, to be confident that it will not affect other functions. Meta-programming concepts are used to solve this problem.

Pragmatic Programmer (pragmatic programmer?) The meta-programming is described as the details in the Jiang code are extracted and put into the meta data. Metadata is typically a configuration file or other data source, and of course metadata can be executable code, as long as the "what" and "how" (how to) clear separation. The idea of this approach is to write code using words that are easily descriptive of the problem domain. The problem domain is the "what" to be described. This type of language is called a domain-specific language (domain specific language) and is abbreviated as a DSL. In the example above, "what" is the rule that shows and hides the fields in the form. The current implementation is to couple the implementation of rules and rules. As demand changes and features increase, the code becomes less clear. If these rules can be drawn out, rule modifications no longer depend on implementation, reducing the frustration of responding to changes in demand. If you use a language that is closer to the problem domain than JavaScript to describe the rule, the problem is greatly simplified.

Writing a DSL starts with thinking about the vocabulary used in the business domain. These words are sometimes different because they describe different roles. For example, programmers, users, business analysts will be different. Before making these assumptions, consider a question: why do these different roles use different words? Different words lead to distorted information in communication. By finding a common vocabulary among groups of people, information transmission can be eliminated, and information distortion can be avoided. This common vocabulary can usually be found in the requirements specification:

Show Us-state when country was "states"
Show province when country is "Canada"
Show Brutus when state is "Ohio" or "Michian"
The DSL should be as consistent as possible with the above description.

It is possible to use the above description directly. The above description is not executable JavaScript code, but can be placed in a text file, read it using JavaScript to parse. This approach, while feasible, may be overly complex. If you use plain text as your DSL, it needs the same flexibility as English. But we want to use it as data and it needs to follow some strict rules. If the DSL itself is executable code, you can simplify the problem. The downside is that a non-program developer might not use this DSL. It is unrealistic to actually write a DSL to non-developers. If the program element is written well, the business person can understand or can modify, it is very good. How to deal with the requirements in the example and turn it into executable code? This may be the most difficult step, with a strong executive nature. In JavaScript, there are two suggestions: string the method together to form a sentence-like structure, and use the method name flexibly. Along this line of thinking, the above business rules can be described as follows:

Show ("Us-state-field"). When ("Country"). Is ("states");

/>show ("Province-field"). When ("Country"). Is ("Canada");
Show ("Brutus"). When ("Us-state"). Is ("Ohio,michigan");

The method names "when" and "is" themselves are not complete, but in the DSL context, these methods are strung together to be very good. You can see that show () returns an object that has a method when (), and when () returns an object that has the method is (). Here is a simple implementation that describes the first rule:

Function Show (Fieldtodisplay) {
return {
When:function (field) {
return {
Is:function (value) {
if ($F (field) = = value) {
$ (Fieldtodisplay). Show ();
}
else{
$ (Fieldtodisplay). Hide ();
}
}
}
}
};
};

The complete code is as follows:

<title>metaprogramming Javascript-example 1</title>
<script src= "Prototype.js" ></script>
<script type= "Text/javascript" charset= "utf-8″>
Function Show (Fieldtodisplay) {
return {
When:function (field) {
return {
Is:function (value) {
if ($F (field) = = value) {
$ (Fieldtodisplay). Show ();
}
else{
$ (Fieldtodisplay). Hide ();
}
}
}
}
};
};

Event.observe (window, "Load", function () {

Event.observe ($ ("Country"), "Change", function () {
Show ("Us-state-field"). When ("Country"). Is ("states");
});

});

</script>

<body>
<form>
<p id= "Country-field" >
<label for= "Country" >Country</label>
<select id= "Country" >
<option>united states</option>
<option>Canada</option>
<option>somewhere else</option>
</select>
</p>

<p id= "Us-state-field" >
<label for= "state" >State</label>
<select id= "Us-state" >
<option>Ohio</option>
<option>Michigan</option>
<option>Kentucky</option>
</select>
</p>
</form>
</body>

The above is just a simple schematic, in the subsequent article will give a complete implementation.

JavaScript meta-programming printing Previous ArticleMaxthon2 Official edition released Next ArticleScopes in JavaScript you may be interested in the article
    • A picturesque JavaScript article (1)
    • In-depth understanding of JavaScript closures (closure) (9)
    • In-depth study of JavaScript call stacks and settimeout usage (9)
    • Scopes in JavaScript (0)
    • JavaScript Library (0)
2 reviews
    1. Java Integrated Network said:2007-08-08 at 16:50

      http://www.javazh.cn/
      Yes, good.

      Reply
    2. Flying Fish said:2007-08-08 at 16:50

      This is good. Study.

      Reply
Leave a comment
  • Log classification
    • Development Technology (57)
    • Slightly smaller (32)
    • Video Podcasts (8)
    • Gossip (174)
    • Flowers (6)
  • Latest logs
    • The ASP. NET menu control displays misplaced solutions under Google Chrome and Safari browser
    • Thinkpage Weather update: IP automatic recognition, weather data source selection
    • The simplest. NET generate random numbers
    • Thinkpage Weather updates: New styles, language auto-recognition, internationalization, PNG weather icons, more weather data
    • The PHP mail function fails the solution by sending mail through the SMTP of Windows
    • HTML Special character descriptor & ISO Latin-1 Character Set
    • Thinkpage weather forecast added real-time preview function
    • The strongest NBA cheerleaders ever turned out!
    • Online gamers and mental illness
    • Hdchina.org Open Registration
  • Latest comments
    • Thank you, you are?
    • I am not very good at praising a person, it seems to write not ...
    • Oh, it should be return B ...
    • Also, to give you a correction: retur ...
    • Tough Ah!!! I guess I just started getting started J ...
    • Some IP judgment is still inaccurate. Please use ...
    • Hello, some of the city's IP recognition problems have ...
    • No, IP is not automatically recognized ah, why ...
    • Buddy Domain is you e dissemble?
    • Not bad
  • Tags creative Beijing blog classmate Online University weather forecast Olympic work advertisement Microsoft Mood Mobile Travel San Francisco Life Network Association network American Party english Apple video design Super mailbox music. Net Adsense AJAX C # flickr GI Glick R Google JavaScript lbslinux MSN Office SharePoint thinkpage TIBCO WAP Windows
  • Log ArchiveSelect Month March 2009 (1)February 2009 (6)December 2008 (1)November 2008 (3)October 2008 (2)September 2008 (3)August 2008 (3)July 2008 (3)May 2008 (2)March 2008 (7)February 2008 (1)January 2008 (3)December 2007 (3) November 2007 (3)October 2007 (2)September 2007 (4)August 2007 (5)July 2007 (2)June 2007 (6)May 2007 (12)April 2007 (6)March 2007 (7)February 2007 (7)December 2006 (3)November 2006 (13)October 2006 (10) September 2006 (7)August 2006 (2)July 2006 (7)June 2006 (8)April 2006 (5)March 2006 (8)February 2006 (4)January 2006 (2)December 2005 (3)November 2005 (4)October 2005 (10)September 2005 (11)August 2005 (12) July 2005 (11)June 2005 (3)May 2005 (9)April 2005 (10)March 2005 (2)February 2005 (2)January 2005 (1) December 2004 (1)November 2004 (1)October 2004 (7)September 2004 (6)August 2004 (4)July 2004 (19)
  • General Information

  • Twitter
    • @putcn so GI is more suitable for enterprise development 2196 days ago
    • The weather forecast has not been updated for a long time. 2197 days ago
    • @putcn Top! 2199 days ago
    • D300 + 35/1.8 Tianjin test shoot http://www.flickr.com/photos/felixwoo/sets/72157616332645361/detail/2199 days ago
    • @longwosion Eric hasn't been here for a long time. 2200 days ago
    Follow me on Twitter
  • Circle of Friends
  • Home link (paid Exchange)
    • Home of China Webmaster
  • Website Management
    • Login
Beijing ICP 备 No. No. 05053527
After 35 queries, it lasted 2.811 seconds and finally generated this page.
Powered by WordPress & designed by felix©2008

Meta-programming using JAVASCRIPT (Web site cannot be played)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.