使用Backbone.js 和 MVC 架构建立一个典型的Hello world项目。虽然是“杀鸡用牛刀了”,毕竟是我第一次使用Backbone.jshtml
jQuery 1.9.1
Undersore.js 1.5.0
Backbone.js
<!doctype html> <html> <head> <meta charset="utf-8"> <title>backbone平常练习</title> </head> <body> <div></div> <script src="js/jquery.min.js"></script> <script src="js/Underscore.min.js"></script> <script src="js/backbone-min.js"></script> <script> // 开启Backbone学习之旅 </script> </body> </html>
在 extend 调用里设置指定的 routes 属性:jquery
var router = Backbone.Router.extend({ routes: { ' ': 'home' } });
Backbone中routes 属性须要下面的格式: ‘path/:param’: 'action',它实现了是当URl是 filename#path/param时, 触发名为action 的函数(在Router 对象里定义)。而后添加一个 home 路由:架构
var router = Backbone.Router.extend({ routes: { ' ': 'home' } });
如今咱们须要添加一个 home 函数:app
var router = Backbone.Router.extend({ routes: { ' ': 'home' } ‘home’: function (){ // 渲染 HTML } });
添加建立和渲染 View 的逻辑。如今先定义 homeView:函数
var homeView = Backbone.View.extend({ });
而后给 homeView 添加属性学习
var homeView = Backbone.View.extend({ el: 'body', teplate: _.template('Hello world!') });
el 是一个保存 jQuery 选择器的字符串,也能够使用'.'做为类和'#'做为ID名。template属性被赋值给传入 Hello World 的 Underscore.js 函数 template 运行的结果。this
渲染 homeView, 咱们使用 this.$el, 这是一个 jQuery 对象,它指向 el 的属性,使用 jQuery.html() 函数使用 this.template() 的结果替换 HTML。 下面是完整的 homeView 代码:code
var homeView = Backbone.View.extend({ el: 'body', template: _.template('Hello World'), render: function (){ this.$el.html(this.template({})); } });
如今咱们返回到 router,添加两行到 home 函数:router
var router = Backbone.Router.extend({ routes: { '': 'home' }, initialize: function (){ // 一些在对象初始化的时候执行的代码 }, home: function (){ this.homeView = new homeView; this.homeView.render(); } });
第一行建立了一个 homeView 对象而且赋值给 router 的 homeView 属性。第二行调用 homeView 对象的 render() 方法,触发 Hello World! 输出。htm
最后,启动总体 Backbone 应用,为了保证 Dom 彻底加载, 用 $(function (){}) 包装器调用 new router:
var app; $(function (){ app = new router; Backbone.history.start(); });
<!doctype html> <html> <head> <meta charset="utf-8"> <title>backbone平常练习</title> </head> <body> <div></div> <script src="js/jquery.min.js"></script> <script src="js/Underscore.min.js"></script> <script src="js/backbone-min.js"></script> <script> var app; var router = Backbone.Router.extend({ routes: { '': 'home' }, initialize: function (){ // 一些在对象初始化的时候执行的代码 }, home: function (){ this.homeView = new homeView; this.homeView.render(); } }); var homeView = Backbone.View.extend({ el: 'body', template: _.template('Hello World'), render: function (){ this.$el.html(this.template({})); } }); $(function (){ app = new router; Backbone.history.start(); }); </script> </body> </html>