您的位置:首页 > 产品设计 > UI/UE

使用require.js和backbone实现简单单页应用实践

2014-11-13 15:37 441 查看

前言

最近的任务是重做公司的触屏版,于是再园子里各种逛,想找个合适的框架做成Web App.看到了叶大(http://www.cnblogs.com/yexiaochai/)对backbone的描述和他做的一个简单框架demo(/article/4682291.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..........
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: