Skip to content

Instantly share code, notes, and snippets.

@kevinkindom
Last active Aug 29, 2015
Embed
What would you like to do?
游戏等级活动
$(function(){
// 处理粘贴板
ZeroClipboard.config({
moviePath: "js/ZeroClipboard.swf"
});
/*var Param = lobby.util.getUrlParams();
var gameId = Param['gameId'];
var serverId = Param['serverId'];
var actId = Param['actId'];*/
var gameId = 'CYSG';
var serverId = 'S310';
var actId = '322777';
var server = 'http://localhost/api/';
var gifListApi = _.template('<%= server %>levelTask.php?gameId=<%= gameId %>&serverId=<%= serverId %>', {server: server, gameId: gameId, serverId: serverId}),
gifImages = _.template('<%= server %>imgs.php?actId=<%= actId %>&sets=<%= sets %>'),
getMissionApi = _.template('<%= server %>joinLevelTasks.php?actId=<%= actId %>&taskParam=<%= taskParam %>'),
receiveApi = _.template('<%= server %>finishTask.php?taskId=<%= taskId %>'),
lotteryApi = _.template('<%= server %>lottery.php?actId=<%= actId %>&pointType=<%= pointType %>'),
getVirtualApi = _.template('<%= server %>myPackage.php?actId=<%= actId %>&orderId=<%= orderId %>'),
packageApi = _.template('<%= server %>myPackage.php?actId=<%= actId %>', {server: server, actId: actId}),
orderApi = _.template('<%= server %>orderAddress.php', {server: server});
// 包裹数据
var packageCollection = Backbone.Collection.extend({
url: packageApi,
parse: function(data){
var ret = [];
_.each(data['data'], function(val, key){
ret.push(_.extend(val, {status: data['status'], message: data['message']}));
});
this.reset(ret);
return ret;
}
});
// 任务图片合集
var gifImageCollection = Backbone.Collection.extend({
parse: function(data){
var ret = [];
_.each(data['data'], function(val, key){
ret.push({image: val});
});
this.reset(ret);
return ret;
}
});
// 任务合集
var gifListCollection = Backbone.Collection.extend({
url: gifListApi,
parse: function(data){
var ret = [];
if(data['status'] == 406 || data['data'] === null) return ret;
var globalVal = {userType: data['data']['userType'], endTime: data['data']['endTime'], serverTime: data['data']['serverTime']};
_.each(data['data']['tasks'], function(val, key){
ret.push(_.extend(val, globalVal));
});
this.reset(ret);
return ret;
}
});
// 获取虚拟卡码
var getVirtual = function(orderId){
var url = getVirtualApi({server: server, actId: actId, orderId: orderId});
return $.ajax({ url: url, type: "get", dataType: "jsonp", jsonp: "callback" });
}
// 填写收货信息
var addAddressView = Backbone.View.extend({
el: $('#bd'),
orderId: '',
template: _.template($('#addAddressTpl').html()),
events: {
'click .close': 'closePopup',
'click .cancel': 'closePopup',
'click .submit': 'submitForm',
'blur .name': 'validateName',
'blur .mobile': 'validateMobile',
'blur .address': 'validateAddress'
},
initialize: function(){
},
set: function(key, value){
if(key != ''){
this[key] = value;
}
},
render: function(){
$('#bd').append(this.template);
},
closePopup: function(){
this.$el.find('.popup').remove();
},
_validateForm: function($el, msg, fn){
if($el.val() == ''){
$el.addClass('error');
$el.parent().find('span.success').remove();
if($el.parent().find('span.error').length <= 0){
$el.after('<span class="error">'+msg+'</span>');
}
return false;
}else{
if(_.isFunction(fn)){
var callback = fn();
if(callback['status'] == 1){
$el.removeClass('error');
$el.parent().find('span.error').remove();
if($el.parent().find('span.success').length <= 0){
$el.after('<span class="success">&emsp;</span>');
}
return true;
}else{
$el.parent().find('span.success').remove();
if($el.parent().find('span.error').length <= 0){
$el.after('<span class="error">'+callback['errormsg']+'</span>');
}else{
$el.parent().find('span.error').text(callback['errormsg']);
}
return false;
}
}
else{
$el.removeClass('error');
$el.parent().find('span.error').remove();
if($el.parent().find('span.success').length <= 0){
$el.after('<span class="success">&emsp;</span>');
}
return true;
}
}
},
validateName: function(){
var $el = this.$el.find('.editInfo').find('.name');
return this._validateForm($el, '姓名不能为空');
},
validateMobile: function(){
var $el = this.$el.find('.editInfo').find('.mobile');
return this._validateForm($el, '手机必须填写', function(){
var mobile = $el.val();
var pattern = /^(?:13\d|15[89])-?\d{5}(\d{3}|\*{3})$/;
if(pattern.test(mobile)){
return {'status': 1};
}else{
return {'status': 0, 'errormsg': '手机格式错误'}
}
});
},
validateAddress: function(){
var $el = this.$el.find('.editInfo').find('.address');
return this._validateForm($el, '收货地址必须填写');
},
submitForm: function(){
//表单验证
if(this._validate()){
var self = this,
$el = this.$el.find('.editInfo'),
name = $el.find('.name').val(),
mobile = $el.find('.mobile').val(),
tel = $el.find('.tel').val(),
email = $el.find('.email').val(),
address = $el.find('.address').val();
var info = {'actId': actId, 'orderId': this.orderId, 'surname': name, 'phone': mobile, 'email': email, 'address': address}
$.ajax({
url: orderApi,
type: "POST",
data: info,
dataType: "jsonp",
jsonp: "callback",
success: function(data){
if(data['status'] == 200){
alert('提交个人资料成功');
}else{
alert(data['message']);
}
self.closePopup();
}
});
}
},
_validate: function(){
if(this.validateName() && this.validateMobile() && this.validateAddress()){
return true;
}else{
return false;
}
}
});
// 抽奖方法
var lotteryFn = function(actId, pointType, elid){
var url = lotteryApi({server: server, actId: actId, pointType: pointType});
$.ajax({
url: url,
type: "get",
dataType: "jsonp",
jsonp: "callback",
success: function(data){
if(data['status'] == 200){
// 变更状态
$($('.gifList').find('.gifInfo').get(elid)).html('领取中,请稍候。');
// 虚拟卡
if(data['data']['awardType'] == 1){
var orderId = data['data']['orderId'];
var maxTry = 5;
var interval = 1000 * 2;
var request = getVirtual(orderId);
request.done(function(data){
var $scope = $($('.gifList').find('.gifInfo').get(elid));
if(data['data'][0]['dispenseResult'] == ''){
var getData = setInterval(function(){
if(maxTry <= 1){
clearInterval(getData);
alert('领取失败,请稍后在“奖励查询”中查看获奖信息。');
$scope.html('<p class="msg2">领取失败,请稍后在“奖励查询”中查看卡号。</p>');
}
var reGet = getVirtual(orderId);
reGet.done(function(data){
if(data['data'][0]['dispenseResult'] != ''){
clearInterval(getData);
}
});
maxTry--;
}, 500);
}else{
$scope.html('<p class="msg2">已成功领取奖励</p><div class="nums" id="n'+elid+'">'+data['data'][0]['dispenseResult']+'</div><div class="copy" data-clipboard-target="n'+elid+'">点击复制</div>');
var clip = new ZeroClipboard($scope.find(".copy"));
}
});
}
// 实物
if(data['data']['awardType'] == 0){
var $scope = $($('.gifList').find('.gifInfo').get(elid));
$scope.html('<p class="msg2">已成功领取奖励</p><div class="nums">任务奖励:'+data['data']['awardName']+'</div>');
// 弹窗填写收货地址信息
var deliveryAddress = new addAddressView();
deliveryAddress.set('orderId', data['data']['orderId']);
deliveryAddress.render();
}
}
}
});
}
// 任务视图
var gifItemView = Backbone.View.extend({
template: _.template($('#gifItem').html()),
events: {
'click .receive': 'receive'
},
initialize: function(){},
render: function(){
var tplData = this.model.toJSON();
if(tplData['taskStatus'] == 100){
tplData['showInfo'] = 0;
}
// tplData['taskStatus'] = 1; // 测试用
this.$el.html(this.template(tplData));
return this;
},
set: function(key, value){
if(key != ''){
this[key] = value;
}
},
receive: function(evt){
var index = this.package.indexOf(this.model);
// 检测任务状态
$.ajax({
url: receiveApi({server: server, taskId: this.model.get('taskId')}),
type: "get",
dataType: "jsonp",
jsonp: "callback",
success: function(data){
// var pointType = gameId+'_'+(parseInt(index)+1);
// lotteryFn(actId, pointType, index); // 测试
if(data['status'] == 200){
var pointType = gameId+'_'+(parseInt(index)+1);
lotteryFn(actId, pointType, index);
}else{
alert(data['message']);
}
}
});
}
});
// 中奖查询视图
var awardQueryView = Backbone.View.extend({
el: $('#bd'),
template: _.template($('#awardQueryTpl').html()),
itemTemplate: _.template($('#awardQueryItemTpl').html()),
events: {
'click .backMain': 'remove'
},
initialize: function(){
},
render: function(){
var self = this;
$.ajax({
url: packageApi,
type: 'get',
dataType: 'jsonp',
jsonp: 'callback',
success: function(data){
var itemHtml = self.itemTemplate({data: data['data']});
self.$el.append(self.template({items: itemHtml}))
}
});
},
remove: function(){
this.$el.find('.awardQuery').remove();
}
});
// 主程序视图
var appView = Backbone.View.extend({
el: $('#bd'),
events: {
'click .query': 'queryAward'
},
initialize: function(){
this.gifList = new gifListCollection;
this.listenTo(this.gifList, 'add', this.add);
this.listenTo(this.gifList, 'reset', this.render);
this.gifList.fetch({dataType: 'jsonp'});
},
add: function(model){
var itemView = new gifItemView({'model': model});
itemView.set('package', this.gifList);
this.$('.gifList').append(itemView.render().el);
},
render: function(){
// 激活任务
this.activeMission();
// 加载礼包图片
this.loadImage();
//载入倒计时
this.countDown();
},
// 查询礼物列表
queryAward: function(){
var awardQuery = new awardQueryView;
awardQuery.render();
},
// 加载礼包图片
loadImage: function(){
var gifImage = new gifImageCollection;
this.listenTo(gifImage, 'reset', function(){
gifImage.each(function(val, key){
$(this.$('.gifList').find('.item').get(key)).find('.pic').append('<img src="'+val.get('image')+'"/>');
});
});
gifImage.fetch({url: gifImages({server: server, actId: actId, sets: this.gifList.at(0).get('userType')}), dataType: 'jsonp'});
},
// 激活任务
activeMission: function(){
// 通过gifList组合参数自动激活所有任务
var taskParam = '';
_.each(this.gifList.where({taskStatus: 0}), function(model){
taskParam += _.template('{"taskId":<%= taskId %>,"gameId":"<%= gameId %>","serverId":"<%= serverId%>"},',
{ taskId: model.get('taskId'), gameId: gameId, serverId: serverId } );
});
//如果还有任务没有被激活,则触发激活
if(taskParam){
taskParam = '['+taskParam.substr(0, taskParam.length-1)+']';
$.ajax({
url: getMissionApi({server: server, actId: actId, taskParam: taskParam}),
type: "get",
dataType: "jsonp",
jsonp: "callback"
});
}
},
// 任务倒计时
countDown: function(){
var serverTime = this.gifList.at(0).get('serverTime'),
endTime = this.gifList.at(0).get('endTime'),
diffTime = endTime - serverTime,
$scope = $('.countdown');
var calc = function(){
var hour = Math.floor(diffTime / 1000 / 60 / 60),
min = Math.floor((diffTime - 1000 * 60 * 60 * hour) / 1000 / 60),
sec = Math.floor(((diffTime - 1000 * 60 * 60 * hour) - 1000 * 60 * min) / 1000);
$scope.find('.hour').text(hour).end().find('.min').text(min).end().find('.sec').text(sec);
}
calc();
if(diffTime > 0){
// 开始倒计时
var countdown = setInterval(function(){
diffTime -= 1000;
if(diffTime < 1000){
clearInterval(countdown);
}
calc();
}, 1000);
}
}
});
var app = new appView;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment