App.Views.Team = Backbone.View.extend({ className : '.team-element', tagName : 'div', model : new App.Models.Team render : function() { // Compile the template var compiledTemplate = _.template($('#teamTemplate').html()); // Model attributes loaded into the template. Template is // appended to the DOM element referred by the el attribute $(this.el).html(compiledTemplate(this.model.toJSON())); } });
Backbone 中最有用且最有趣的一个功能是将 render() 方法绑定到模型的变更事件中,如 所示。
清单 21. Render() 方法绑定到模型变更事件// In the following view, el value is 'div.team-element' App.Views.Team = Backbone.View.extend({ model : new App.Models.Team, initialize : function() { this.model.bind("change", this.render, this); } })
上述代码将 render() 方法绑定到一个模型的变更事件中。当模型发生更改时,会自动触发 render() 方法,从而节省数行代码。从 Backbone 0.5.2 开始,bind() 方法就开始接受使用第三个参数来定义回调函数的对象。(在上述示例中,当前视图是回调函数 render() 中的对象)。在 Backbone 0.5.2 之前的版本中,必须使用 underscore.js 中的 bindAll 函数,如 所示。
清单 22. _.bindAll() usage// In the following view, el value is 'div.team-element' App.Views.Team = Backbone.View.extend({ initialize : function() { _.bindAll(this, "render"); this.model.bind("change", this.render); } })
Backbone 视图中,通过视图中的 DOM 对象监听事件是比较容易的。对于实现这一点,events 属性很是方便的,如 所示。
清单 23. 事件属性App.Views.Team = Backbone.View.extend({ className : '.team-element', tagName : 'div', events : { "click a.more" : "moreInfo" }, moreInfo : function(e){ // Logic here } })
events 属性的每个项均由两部分构成:
在 中,当用户通过 DIV 中的类 more 以及类 team-element 点击链接时,会调用函数 moreInfo。
结束语MVC 模式可以为大型 JavaScript 应用程序提供所需的组织化代码。Backbone 是一个 JavaScript MVC 框架,它属于轻量级框架,且易于学习掌握。模型、视图、集合和路由器从不同的层面划分了应用程序,并负责处理几种特定事件。处理 Ajax 应用程序或者 SPI 应用程序时,Backbone 可能是最好的解决方案。
下载描述名字大小
本文源代码IBM_Backbone.zip45KB
参考资料 学习
developerWorks: 登录
标有星(*)号的字段是必填字段。
在您首次登录 developerWorks 时,会为您创建一份个人概要。您的个人概要中的信息(您的姓名、国家/地区,以及公司名称)是公开显示的,而且会随着您发布的任何内容一起显示,除非您选择隐藏您的公司名称。您可以随时更新您的 IBM 帐户。
所有提交的信息确保安全。
选择您的昵称
当您初次登录到 developerWorks 时,将会为您创建一份概要信息,您需要指定一个昵称。您的昵称将和您在 developerWorks 发布的内容显示在一起。
昵称长度在 3 至 31 个字符之间。 您的昵称在 developerWorks 社区中必须是唯一的,并且出于隐私保护的原因,不能是您的电子邮件地址。
标有星(*)号的字段是必填字段。
所有提交的信息确保安全。
文章、教程、演示,帮助您构建、部署和管理云应用。
立即加入来自 IBM 的专业 IT 社交网络。
为灾难恢复构建应用,赢取现金大奖。
static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=10
Zone=Web development, Open source
ArticleID=833324
ArticleTitle=开始学习 Backbone
publish-date=09062012