使用require.js和backbone实现简单单页应用实践
前言
最近的任务是重做公司的触屏版,于是再园子里各种逛,想找个合适的框架做成Web App.看到了叶大(http://www.cnblogs.com/yexiaochai/)对backbone的描述和他做的一个简单框架demo(http://www.cnblogs.com/yexiaochai/p/3837713.html),于是拿来主义,把源码下载了.
项目框架
项目使用VS2012+MYSQL开发,MVC架构,没有叶大那么厉害,只能做做简单应用,下面的做的一个列表和详细页面的JS代码块.
主要JS代码块:
<script type="text/javascript"> var IndexModel = Backbone.Model.extend({}); var IndexList = Backbone.Collection.extend({ model: IndexModel, parse: function (data) { return (data && data.data) || {} }, setComparator: function (type) { this.comparator = function (item) { return Math.max(item.attributes[type]); } } }); var Detail = Backbone.View.extend({ el: $("#contents"), template: _.template($(‘#detail-template‘).html()), events: { ‘click #js-return‘: function () { this.app.forward(‘index‘); } }, initialize: function (app) { this.app = app; this.render(); }, render: function () { var scope = this; var id = this.app.id; var model = this.app.model; $.ajax({ url: ‘@Url.Action("GetContentById", "Home")‘, type: ‘get‘, data: { id: id }, dataType: ‘json‘, timeout: 1000, error: function () { location.href = ‘/‘; }, success: function (data) { if (data && data.data) { model.set(‘value‘, data.data); $(".viewport").hide(); $(‘#viewport_detail‘).show(); $(‘#id_viewport_detail‘).html(scope.template(model.toJSON())); } } }); } }); var Index = Backbone.View.extend({ el: $(‘#indexlist‘), template: _.template($(‘#indexlist-template‘).html()), events: { ‘click .js_largeimg‘: function (e) { var el = $(e.currentTarget); var index = el.attr(‘data-index‘); var id = el.attr(‘data-id‘); var model = this.list.models[index]; this.app.model = model; this.app.id = id; this.app.forward(‘detail/‘+id); } }, initialize: function (app) { this.app = app; var scope = this; var curpage = 1; var pageSize = 10; this.list = new IndexList(); this.list.url = ‘@Url.Action("GetIndexList", "Home")‘; this.list.fetch({ success: function () { scope.render(); } }); this.listenTo(this.list, ‘all‘, this.render); }, render: function () { var models = this.list.models; var html = ‘‘; for (var i = 0, len = models.length; i < len; i++) { models[i].index = i; html += this.template(_.extend(models[i].toJSON(), { index: i })); } $(".viewport").hide(); $("#viewport_index").show(); $("#indexlist").html(html); var s = ‘‘; } }); var App = Backbone.Router.extend({ routes: { "": "index", // #index "index": "index", // #index "detail/:id": "detail" // #detail }, index: function () { var index = new Index(this.interface); }, detail: function (id) { var detail = new Detail(this.interface); detail.app.id = id; }, initialize: function () { }, interface: { forward: function (url) { window.location.href = (‘#‘ + url).replace(/^#+/, ‘#‘); } } }); var app = new App(); Backbone.history.start(); var s = ‘‘; </script>
实现效果不错,继续努力不断优化ing..........
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。