关于MVVM的理论,网上说的已经比较多了,最近需要快速开发开发一个app,采用了appcan,用MVVM模式开发起来还是比较顺手的,学习周期大约一周,先开发了接口,然后开始app开发,对于scrollview的下拉刷新,官方是有例子的,比较容易实现,但是上拉加载和分页这些没有完整的例子啥的,会耽误点时间,我把代码粘出来,希望能帮一些同类节省点时间,话不多说,上代码:
appcan.ready(function() {
$.scrollbox($("body")).on("releaseToReload",
function() { //After Release or call reload function,we reset the bounce
$("#ScrollContent_5VO035").trigger("reload", this);
}).on("onReloading",
function(a) { //if onreloading status, drag will trigger this event
}).on("dragToReload",
function() { //drag over 30% of bounce height,will trigger this event
}).on("draging",
function(status) { //on draging, this event will be triggered.
}).on("release",
function() { //on draging, this event will be triggered.
}).on("scrollbottom",
function() { //on scroll bottom,this event will be triggered.you should get data from server
$("#ScrollContent_5VO035").trigger("more", this);//看这里,需要在这里添加上拉加载更多的事件触发
}).reload();
})
Services层面:
var Service_artist = new MVVM.Service({
pretreatment: function(data, option) {
return data;
},
dosuccess: function(data, option) {
closeLoading();
return data.data;
},
doerror: function(e, err, option) {
closeLoading();
appcan.window.openToast({
msg:'请求数据出错',
duration:3000,
position:5,
type:0
});
return err;
},
validate: function(data, option) {
if(data.code == 1000){
return 0;
}else{
return 1;
}
},
ajaxCall: function(data, option) {
var self = this;
appcan.request.ajax({
url: '你的api接口地址',
type: "GET",
data: '',
dataType: "json",
contentType: "application/x-www-form-urlencoded",
success: function(data) {
var res = self.validate(data, option);
if (!res) option.success(self.dosuccess(data, option));
else option.error(self.doerror(data, res, option));
},
error: function(e, err) {
option.error(self.doerror(e, err, option));
}
});
}
});
Model层面:
var Model_Collection_artist = MVVM.Model.extend({
defaults: {},
computeds: {},
sync: function(method, model, options) {
switch (method) {
case "create":
break;
case "update":
break;
case "patch":
break;
case "delete":
break;
default:
break;
}
}
});
var Collection_artist = new(MVVM.Collection.extend({
initialize: function() {
return;
},
parse: function(data) {
//console.log(data);
totalpage = data.totalpage; //接口返回的总页数
return data.writers_list;//这是个JSON的array,包含了构造model对象的JSON对象
},
model: Model_Collection_artist,
sync: function(method, collection, options) {
switch (method) {
case "read":
openLoading();
Service_artist.request(options.attrs, options);
break;
default:
break;
}
}
}))();
ViewModel层面:
var ViewModel_artist = new(MVVM.ViewModel.extend({
el: "#ScrollContent_5VO035",
events: {
"reload": function(ev, param) {
totalpage = 0;
curpage = 1;
this.collection.fetch({
"success": function() {
//debugger;
param.reset();
},
"error": function() {
//debugger;
param.reset();
}
})
},
"more":function(ev,param){ //关键的代码就在这里
//alert(curpage+"======"+totalpage);
if(curpage