日期:2014-05-16 浏览次数:20513 次
有些同学反映说,需要看太多的篇章才能明白如何使用JavaScriptMVC来开发,可不可以 用一篇把主要用到技术介绍一下,这样就可以快速入门,并且可以快速用到开发项目的。 这篇文章就是这个目的,下面我们来讲述如何快速开发。 也就是我们习惯的的开发,自己创建项目,模块等。
不过不管怎样,我们都需要下载JavaScriptMVC包,下载它,然后把它解压到我们的项目中。 解压完JavaScriptMVC包后,我们看到4个文件夹,文件列表如下:
documentjs - documentation engine funcunit - testing app jquery - jquery and jQueryMX plugins steal - dependency management js - JS command line for Linux/Mac js.bat - JS command line for Windows?
注意:这个库文件夹,我们统称为根目录。
获取JavaScriptMVC运行
JMVC使用steal来管理。Steal加载脚本。像JMVC中使用到特性$.Controller和$.View,steal是这样加载的:
steal('jquery/controller','jquery/view/ejs',function(){
//code that uses controller and view goes here
})
?
在使用steal之前,你需要把steal脚本添加到你的页面中。在根目录下创建一个todos文件夹,
然后在这个文件夹下面 创建一个todos.html和todos.js文件:
ROOT\
documentjs\
jquery\
funcunit\
steal\
todos\
todos.js
todos.html
?
修改todos.html文件,把steal.js和todos.js脚本加载进来:
<!DOCTYPE html>
<html>
<head></head>
<body>
<ul id='todos'></ul>
<input id='editor'/>
<script type='text/javascript'
src='../steal/steal.js?todos/todos.js'>
</script>
</body>
</html>
?
在浏览器中打开这个页面,然后使用debug工具可以看到steal.js和todos.js已经加载进来。
Steal steal([paths])
Steal是使用来加载脚本,样式,甚至CoffeeScript,LESS和模板到你的程序中。当然这个只是Steal其中的一个特性。 Path是假设相对于根目录的。这就意味下述加载jquery/class/class.js文件是没有问题的:
steal('jquery/class/class.js');
?
?
你可以使用./来加载相对于目前文件夹的文件:
steal('./helpers.js')
?
?
Steal也支持CSS,下述就是加载todos/todos.css:
steal('./todos.css')
?
?
因为加载像jquery/class/class.js这种路径太普遍,如果你没有提供后缀名为.js的文件,Steal将会加载把文件夹名称加.js后缀的文件。 像下述也是加载jquery/class/class.js文件:
steal('jquery/class')
?
?
Steal是一个异步的载入器,所以你不能这样写:
steal('jquery/class')
$.Class
?
应该是这样:
steal('jquery/class', function(){
$.Class
})
?
对于这个程序,我们将加载jQueryMX的常用插件。添加最终结果如下述:
steal('jquery/class',
'jquery/model',
'jquery/dom/fixture',
'jquery/view/ejs',
'jquery/controller',
'jquery/controller/route',
function($){
})
?
?
下面讲述的都当我们开发todos程序时需要使用到的各个插件。
$.Class
$.class([name],[staticProperties],[prototypeProps])
?
从构造函数可以看出$.Class是使用来创建一个对象的。
$.Controller和$.Model都使用到它。
创建自定义类,调用$.Class,然后给传递以下参数:
1、name 类名
2、staticProperties 静态属性
3、prototypeProperties 成员属性
$.Class使用的原型链,所以子类很容易扩展它,如下:
steal('jquery/class', function(){
$.Class("Todo",{
init : function(){},
author : function(){ ... },
coordinates : function(){ ... },
allowedToEdit: function(account) {
return true;
}
});
Todo('PrivateTodo',{
allowedToEdit: function(account) {
return account.owns(this);
}
})
});
?
$.Class还提供了在父类中使用简短的a_super方法可以调用父类的方法:
var SecureNote = Todo({
allowedToEdit: function(account) {
return this._super(account) &&
this.isSecure();
}
})
?
构造器/初始化 new Class(arg1,arg2)
当一个类的构造函数被调用时,$.Class将实例化并且调用init函数,它接收参数。
$.Class('Todo',{
init : function(text) {
this.text = text
},
read : function(){
console.log(this.text);
}