当前位置: 代码迷 >> 综合 >> JSConf 2010 (二):JS的模式编程、微格式 和 MooTools
  详细解决方案

JSConf 2010 (二):JS的模式编程、微格式 和 MooTools

热度:88   发布时间:2023-12-10 01:39:43.0

模式编程(programming to the patterns)

JS的通用库最基本的目的是给你解决浏览器兼容性差异,Prototype和JQuery是做得最好的两个库。

JQuery对Dom的DSL化封装,还有对method chain的大量使用,几乎让你感觉在声明行为,所以它让非常多的对啰嗦的Dom编程厌烦的前端程序员迅速“上瘾”。但是,我们知道DSL化的JQuery还不够,因为它很好的解决了可读,但是并不一定容易维护(尤其是过度使用method chaning)。

其实Javascript的各种Widget库(如ExtJS、Dojo和YUI的widget库)都做到更好的复用。缺点是目前的widget库中的高级控件都严重的绑架了Dom结构,造成自己修改Dom结构比较麻烦。而没有使用Micro Format这样的基于标准的弱耦合,这是一个很大的问题。

顺便提一下,MicroFormat(微格式)是什么,WikiPedia上面有描述:

A Microformat (sometimes abbreviated μF or uF) is a way of adding simple semantic meaning to human-readable content which is otherwise, from a machine's point of view, just plain text. They allow data items such as events, contact details or locations, on HTML (or XHTML) web pages, to be meaningfully detected and the information in them to be extracted by software, and indexed, searched for, saved or cross-referenced, so that it can be reused or combined.

Both Firefox 3 and Internet Explorer 8 will support micro formats natively. If you cannot wait for the next version of Firefox or IE, then you can download the Operator micro format extension for Firefox and start testing your site.

这是一个最简单的从POSH(Plain Old Semantic HTML)变成hCard Micro Format的方法:

这样一来,这些本来含义难以使用爬虫和机器猜测的片段都有了具体含义。

不好意思,扯远了,让我们再回到模式编程上来。

会上提倡更多地采用模式编程,比如从OO开始,比如从继承一个类开始:

JS 类的关键切面包括:简单继承关系;把逻辑打碎成小的方法;把函数打碎成小的类;为编组的函数建立控制类;使用类库和事件库;必要时重构。

这样一段绑定事件的JS逻辑:

就可以这样进行模式编程,把整个行为逻辑定义为一个类,然后把绑定分别定义为方法,代码倒是复杂了,不过逻辑清晰不少,这个见仁见智吧。我还是觉得所有的重构、模式化和泛化都要建立在价值的基础之上:

未来如果子类出现:

最后他建议使用MooTools,它可以把JS中许多事情放在框架里面做完,让接口的使用更加简单,鼓励你重用代码,并写流畅、扩展性好和复用性好的代码。

 

MooTools(http://mootools.net/)是一个简洁,模块化,面向对象的开源JavaScript web应用框架。 它为web开发者提供了一个跨浏览器js解决方案。在处理js css html时候。它提供了一个比普通js更面向对象的document API。

MooTools的优点:

1.灵活,模块化的框架,用户可以选择自己需要的组件。

2.MooTools符合OO的思想,使代码更强壮,有力,有效。

3.高效的组件机制,可以和flash进行更好的交互。

4.对于DOM的扩展增强,使开发者更好的利用document。

最后用一个MooTools的实例结束本文:

var Animal = new Class({

     initialize: function(name){

         this.name = name;

     }

});

var Cat = new Class({

     Extends: Animal,

     talk: function(){

         return 'Meow!';

     }

});

var Dog = new Class({

     Extends: Animal,

     talk: function(){

         return 'Arf! Arf';

     }

});

var Animals = {

     a: new Cat('Missy'),

     b: new Cat('Mr. Bojangles'),

     c: new Dog('Lassie')

};

for(var animal in Animals)

           alert(animal.name + ': ' + animal.talk());

// alerts the following:

// Missy: Meow!

// Mr. Bojangles: Meow!

// Lassie: Arf! Arf!

  相关解决方案