【PC网站前端架构探讨系列】关于中小型PC网站前端架构方案的讨论与实践

时间:2021-06-26 09:55:20

目   录

  1.遇到的问题

  2.目标

  3.探讨

  4.架构设想

  5.流程

6.初步实现

  7.存在问题

  8.最后

遇到的问题

我在这个系列上篇文章 已经讲解并开始逐步应用模块化思想,不知大家还记不记得,题目:【PC网站前端架构探讨系列】结合公司网站首页,谈前端模块化开发与网站性能优化实践 。但是,仍然会存在下列问题:

问题1----模块内部脚本和页面联系密切

     问题2----所有脚本文件集中放于一个目录,脚本目录不清晰,没有层次

   当然还有其他很多问题,但就以上两大问题来说,会对后期代码维护带来不便!

目   标

      尽量将页面和脚本进行分离,以及方便开发人员维护管理,形成一个固定的代码规范;其二,项目的结构清晰,层次明确,功能突出。所以,需要设计一个合理的前端架构来解决当前以及后期会遇到的问题

探   讨

思想方面:

    针对耦合性问题,业界流行的新一种架构思想——“MVC””MVVC”,但大多这种思想用于WAP开发中,国内很少的PC网站有用过,比如,有道好像用的是Backbone框架…

技术角度:

       在seajs模块划分的基础上

1. backbone+underscore(MVC)

2. knockout(MVVM)

       目前这两种用的较多,而且社区文档比较多,但是都比较适合单页面的应用,最主要就是开发方式会有很大转变….很难上手…感觉不太适合普通中小型的PC网站开发以及后期维护

下面列出相关示例代码:(Backbone)

    define('module/home/index', ['backbone'], function(reuqire) {
var Backbone = reuqire('backbone');
App.Models.Home = Backbone.Model.extend({}); App.Collections.Home = Backbone.Collection.extend({
model: App.Models.Home
}); App.Views.Home = Backbone.View.extend({
el: '#container',
initialize: function(c) {
this.Collections = c;
this.render();
},
render: function() {
var html = '';
this.Collections.each(function(m) {
html += '<div><a href="' + m.get('link') + '">' + m.get('name') + '</a></div>';
});
this.$el.html(html);
}
}) return function() {
//模拟数据
var hc = new App.Collections.Home();
hc.add([
{'name': '加载模块A', 'link': '#at/m/a/name:moduleA/other:nothing'},
{'name': '加载模块B', 'link': '#at/m/b'}
]);
new App.Views.Home(hc);
}
});

紧接着:(knockout)

       <html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Knockout学习一</title>
<script src="Scripts/knockout-3.0.0.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
</head>
<body> <div>
<span data-bind="text: personName"></span>
</div> </body>
<script type="text/javascript">
var myViewModel = {
personName: ko.observable('张三'),
personAge: ko.observable(12)
}; $(function() {
ko.applyBindings(myViewModel);
}); </script>
</html>

  另外,一个完整的前端框架要包括以下方面:

  1.  解耦

   2.  模块化

  3.  统一的代码书写结构

   4.  组件库

   5.  事件处理机制   ……

  目前互联网发展迅速,技术更新太快,所以,针对以上方面使用目前的技术手段,完全可以实现,就是好多文档不全,教程不清晰,关键比较零散,不同技术组合起来会遇到很多问题,问题再多,时间充足的话,也会找到解决的办法。我这里简单说下解决的思路:

   1.  解耦问题--可以使用模板来达到业务和页面分离

  2.  模块化问题--模块化技术好多,requireJS、seajs等,我这里用的是seajs

  3.  代码结构—json格式

  4.  组件库—define封装,定义成seajs模块,定义属性、选择器、方法、事件等

  5.  事件处理机制 —事件的单独封装,统一的注册机制,调用机制(kissy 做的很好,个人还没研究透)

下面先做个简单的架构设想 吧!

架构设想

【PC网站前端架构探讨系列】关于中小型PC网站前端架构方案的讨论与实践

这里看图就不多讲了,直接看下面的关系吧!

 流  程

    模块之间的关系以及调用流程如下:

【PC网站前端架构探讨系列】关于中小型PC网站前端架构方案的讨论与实践

  

初步实现

说到技术,推荐多去学习下百度阿里腾讯等的前端技术,相对比较贴地气,比较赶潮流. .比如,之前在学习seajs 的时候,无意中发现一些网站的脚本从风格、写法、思想上,都值得我学习一下。所以,我经常特意把上面的代码扒下来,研究一番…..

  废话不多说,这里把我部分代码分享出来:

1.package/main.js (核心工具类库)

 /**
* 核心工具类 文件 v20151023
*/
(function() {
var mods = [],
version = parseFloat(seajs.version);
define(["lib/jquery"],function(require, exports, module) {
var uri = module.uri || module.id,
m = uri.split("?")[0].match(/^(.+\/)([^\/]*?)(?:\.js)?.J/i),
root = m && m[1],
name = m && "./" + m[2].substring(0,m[2].length),
i = 0,
len = mods.length,
curr, args, undefined;
name = name.replace(/\.r[0-9]{15}/, "");
for (; i < len; i++) {
args = mods[i];
if (typeof args[0] === "string") {
name === args[0] && (curr = args[2]);
args[0] = root + args[0].replace("./", "");
version > 1 && define.apply(this, args);
}
}
mods = [];
require.get = require;
return typeof curr === "function" ? curr.apply(this, arguments) : require;
});
define.pack = function() {
mods.push(arguments);
version > 1 || define.apply(null, arguments)
}
})();
define.pack("./request", ["lib/jquery","./random","./domains"], function(require, exports, module) {
var Random = require("./random");
var J = require("lib/jquery");
var Domains=require("./domains");
var MOD = {
_Config: {
domain: Domains.base
},
request:function(conf){
var conf = {
type: conf.type,
async: conf.async || false,
url: this._Config.domain+conf.url,
dataType: conf.dataType || 'json',
data: conf.data || {},
beforeSend: conf.before,
success: conf.success,
complete: conf.complete,
error: conf.error
};
J.ajax(conf);
},
get: function(conf) {
return MOD.request({
type: 'get',
async: conf.async,
url: conf.url,
dataType: conf.dataType,
data: conf.data,
beforeSend: conf.callback.beforeSend,
success: conf.callback.success,
complete: conf.callback.complete,
error: conf.callback.error
})
},
post: function(conf) {
return MOD.request({
type: 'post',
async: conf.async,
url: conf.url,
dataType: conf.dataType,
data: conf.data,
beforeSend: conf.callback.beforeSend,
success: conf.callback.success,
complete: conf.callback.complete,
error: conf.callback.error
})
},
jsonp: function(conf) {
conf.dataType = "jsonp";
return MOD.request(conf)
},
src: function(conf) {
conf = conf || {};
var defConfig = this._Config;
var url, data = {
domain: conf.url || defConfig.domain,
_: Random()
};
if (data.domain) {
url = data.domain+"?_=" + data._;
(new Image).src = url
}
}
};
return MOD;
});
define.pack("./random", [], function(require, exports, module) {
var MOD = function() {
var rs = (new Date).getTime() + Math.ceil(Math.random() * 1E4);
return rs;
};
return MOD;
});
define.pack("./template", ['lib/jquery'], function(require, exports, module) {
var J = require("lib/jquery");
var MOD = {
parse: function() {
var cache = {};
return function(str, data) {
if (typeof str === "function") return data ? str(data) : str;
var fn = !/\W/.test(str) ? cache[str] = cache[str] || arguments.callee.call(this, document.getElementById(str).innerHTML) : new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + "with(obj){p.push('" + str.replace(/[\r\t\n]/g,
" ").split("<%").join("\t").replace(/((^|%>)[^\t]*)'/g, "J1\r").replace(/\t=(.*?)%>/g, "',J1,'").split("\t").join("');").split("%>").join("p.push('").split("\r").join("\\'") + "');}return p.join('');");
if (data){
return fn(data);
} else {
return fn;
}
}
}(),
render:function(opts){
var html = '';
var conf = J.extend({
container: opts.container instanceof jQuery ? opts.container : J(opts.container),
tmpl: typeof(opts.tmpl) =='string' ? opts.tmpl
: opts.tmpl.join(''),
options: opts.options || {}
}, {});
html += MOD.parse(conf.tmpl,conf.options);
conf.container.html(html);
}
};
return MOD;
});
define.pack("./browser",["lib/jquery"],function(require,exports,module){
var J = require("lib/jquery");
var MOD={
_getBrower:function(){
var ua = navigator.userAgent,
jqBrowser = J.browser,
jqVersion = jqBrowser.version,
browser = '',
ver = '';
if (jqBrowser.msie) {
browser = 'ie';
ver = Math.floor(jqVersion);
if (ver < 6) {
ver = 6;
}
if (ver > 10) {
ver = 10;
}
} else if (jqBrowser.webkit) {
browser = 'safari';
if (ua.indexOf('Chrome') !== -1) {
browser = 'chrome';
}
} else if (jqBrowser.mozilla) {
browser = 'firefox';
} else if (jqBrowser.opera) {
browser = 'opera';
}
if (!browser) {
browser = 'other';
ver = '';
}
return '' + browser + ver;
},
isIE:function(v){
v = v || J.browser.version;
return this._getBrowser=='ie'+v.toString();
}
};
return MOD;
});
define.pack('./domains',[],function(require,exports,module){
var MOD={
base: basePath || "https://www.ddshenbian.com"
};
return MOD;
});
define.pack("./cookie", ["lib/jquery", "./domains"], function(require, exports, module) {
var J = require("lib/jquery");
var Domains = require("./domains"); function MOD(name, value, options) {
if (typeof value != "undefined") {
options = options || {
"domain": Domains.base
};
if (value === null) {
value = "";
}
var expires = "";
if (options.expires && (typeof options.expires == "number" || options.expires.toUTCString)) {
var date;
if (typeof options.expires == "number") {
date = new Date;
date.setTime(date.getTime() + options.expires *
1E3)
} else date = options.expires;
expires = "; expires=" + date.toUTCString()
}
var path = options.path ? "; path=" + options.path : "";
var domain = options.domain ? "; domain=" + options.domain : "";
var secure = options.secure ? "; secure" : "";
document.cookie = [encodeURIComponent(name), "=", encodeURIComponent(value), expires, path, domain, secure].join("")
} else {
var cookieValue = null,
name = encodeURIComponent(name);
if (document.cookie && document.cookie != "") {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = J.trim(cookies[i]);
if (cookie.substring(0, name.length +
1) == name + "=") {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break
}
}
}
return cookieValue
}
}
return MOD;
});
define.pack("./html", [], function(require, exports, module) {
var MOD = function() {
var encodeMap = {
reg: /([&"'<>])/gmi,
"&": "&amp;",
'"': "&quot;",
"'": "'",
"<": "&lt;",
">": "&gt;"
},
decodeMap = {
reg: /(&lt;)|(&quot;)|(')|(')|(')|(&amp;)|(&gt;)/gim,
"&lt;": "<",
"&gt;": ">",
"&quot;": '"',
"'": "'",
"'": "'",
"'": "'",
"&amp;": "&"
},
encode = function(J0, c) {
return encodeMap[c]
},
decode = function(c) {
return decodeMap[c]
};
return {
htmlEncode: function(str) {
if (typeof str != "string") str = str + "";
return str.replace(encodeMap.reg,
encode)
},
htmlDecode: function(str) {
if (typeof str != "string") str = str + "";
return str.replace(decodeMap.reg, decode)
}
}
}();
return MOD;
});
define.pack("./error", [], function(require, exports, module) {
function MOD(mname,msg) {
throw "DD.error[" + mname + "]\u8f93\u51fa\u9519\u8bef\uff1a" + msg;
}
return MOD;
});
define.pack("./log", ["lib/jquery"], function(require, exports, module) {
var J = require("lib/jquery");
var MOD = function() {
var logPanel, logPanelBd;
return function() {
try {
if (J.browser.msie) console.log([].slice.call(arguments).join(""));
else console.log.apply(console, [].slice.call(arguments))
} catch (e) {}
}
}();
return MOD;
});
define.pack("./helper", ["lib/jquery", "./cookie"], function(require, exports, module) {
var J = require("lib/jquery");
var Cookie = require("./cookie");
var MOD = {
getURLArgs: function(str, k) {
str = str ? str : location.href;
var s = str.indexOf("?");
var e = str.indexOf("#") == -1 ? str.length : str.indexOf("#");
var r = {};
if (s != -1) {
var ts = str.substring(s + 1, e);
ts = ts.split("&");
var t;
for (var i = 0; i < ts.length; i++) {
t = ts[i].split("=");
if (t.length == 2) r[t[0]] = t[1]
}
}
if (k) return r[k] ? r[k] : false;
return r
},
isEmpty: function(v) {
if (v != null && (typeof v ==
"object" || typeof v == "function")) {
if (J.isArray(v) && v.length == 0) return true;
return false
}
return "" == v || undefined == v || null == v ? true : false
},
filterXSS: function(cont) {
cont = cont.replace(/&/g, "&amp;");
cont = cont.replace(/</g, "&lt;").replace(/>/g, "&gt;");
cont = cont.replace(/\'/g, "'").replace(/\"/g, "&quot;");
return cont
},
str2Args: function(query, split) {
var args = {};
query = query || "";
split = split || "&";
var pairs = query.split(split);
for (var i = 0; i < pairs.length; i++) {
var pos = pairs[i].indexOf("=");
if (pos == -1) continue;
var argname = pairs[i].substring(0, pos);
var value = pairs[i].substring(pos + 1);
args[argname] = this.filterXSS(decodeURIComponent(value))
}
return args
},
args2Str: function(args, split) {
split = split || "&";
var key, rtn = "",
sp = "";
for (key in args) {
rtn += sp + key + "=" +
encodeURIComponent(args[key]);
sp = split
}
return rtn
},
formatDate: function(mDate, fmt) {
var o = {
"M+": mDate.getMonth() + 1,
"d+": mDate.getDate(),
"h+": mDate.getHours() % 12 == 0 ? 12 : mDate.getHours() % 12,
"H+": mDate.getHours(),
"m+": mDate.getMinutes(),
"s+": mDate.getSeconds(),
"q+": Math.floor((mDate.getMonth() + 3) / 3),
"S": mDate.getMilliseconds()
},
week = {
"0": "\u65e5",
1: "\u4e00",
2: "\u4e8c",
3: "\u4e09",
4: "\u56db",
5: "\u4e94",
6: "\u516d"
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.J1, (mDate.getFullYear() + "").substr(4 - RegExp.J1.length));
if (/(E+)/.test(fmt)) fmt = fmt.replace(RegExp.J1, (RegExp.J1.length > 1 ? RegExp.J1.length > 2 ? "\u661f\u671f" : "\u5468" : "") + week[mDate.getDay() + ""]);
for (var k in o)
if ((new RegExp("(" + k + ")")).test(fmt)) fmt = fmt.replace(RegExp.J1, RegExp.J1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
return fmt;
},
toThousands:function(num) {
var num = (num || 0).toString(), re = /\d{3}J/, result = '';
while ( re.test(num) ) {
result = RegExp.lastMatch + result;
if (num !== RegExp.lastMatch) {
result = ',' + result;
num = RegExp.leftContext;
} else {
num = '';
break;
}
}
if (num) { result = num + result; }
return result;
}
};
return MOD;
});
define.pack("./response",["./error"],function(require, exports, module){
var error = require("./error");
var MOD=function(res,autoCode){
var code = res.code;
if(code){
return code == (autoCode || 1)?(res.obj || res.msg):res.msg;
}
error();
};
return MOD;
});
define.pack("./json",[],function(require, exports, module){
return {
isJSON : function(obj){
var isjson = typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
return isjson;
}
};
});
define.pack("./user",['jquery','./cookie','./json','./domains','./template'],function(require, exports, module){
var Domains = require("./domains"),
json = require("./json"),
template = require("./template"),
cookie = require("./cookie"),
J = require("jquery");
var MOD = {
logout: function() {
J('#header').delegate('a#quit', 'click', function() {
seajs.use("package/data", function(d) {
if(d.logout == 0){
window.location.reload();
}
})
})
},
login: function(){
var that = this;
var loginTmpl = ['<a class="uname fr" id="_userName" href="<%=domain%>/auth/account/myaccount_index">','<%=_userName%>','<a class="msg-link" id="msgbox" style="<%=_isShow%>">','<em>','<%=_msgNum%>','</em>','</a>','</a>',
'<ul class="dropdown-menu" role="menu" aria-labelledby="userInfoBox">',
'<li role="presentation">','<a role="menuitem" tabindex="-1" id="accountURI" href="<%=domain%>/auth/account/<%=_accountURI%>">','我的账户','</a>', '</li>',
'<li>', '<a role="menuitem" tabindex="-1" href="<%=domain%>/auth/msgManager/index" class="msg-link">','消息','(','<em>','</em>',')','</a>','</li>',
'<li>','<a role="menuitem" tabindex="-1" id="quit">','退出登录','</a>','</li>','</ul>'].join('');
seajs.use("package/data", function(d) {
var obj = json.isJSON(d.uinfo) ? d.uinfo : {};
that.uinfo(loginTmpl,obj);
})
},
uinfo: function(loginTmpl,obj){
var conf = J.extend({
domain: Domains.base,
}); if (obj.loginFlag == 1) {
J.extend({
_isShow: '',
_accountURI: '#',
_userName: 'hi!' + obj._userName,
_msgNum: obj._msgNum
},conf); J("#homelogin").show();
J("#homeunlogin").hide();
if (conf._msgNum != 0) {
conf._isShow = 'display:"none"';
}
if (obj._userType == 2) {
conf._accountURI = 'companyaccount_index';
} else {
conf._accountURI = 'myaccount_index';
}
var opts = {
container: '#homelogin',
tmpl: loginTmpl,
options: conf
};
template.render(opts);
} else {
J("#homelogin").hide();
J("#homeunlogin").show();
}
},
toTop: function(){
J("#toTop").on('click', function() {
J('html,body').animate({
scrollTop: 0
}, 700)
});
J(window).scroll(function() {
var s = J(window).scrollTop();
if (s > 600) {
J("#toTop").fadeIn(100)
} else {
J("#toTop").fadeOut(200)
}
})
},
_getCookieOpt: function(setting) {
setting = setting || {};
var opt = {
domain: Domains.base,
expires: 60 * 60 * 24 * (setting.expires || 1),
path: '/'
};
return opt;
},
utm2cookie: function(opts){
var conf = J.extend({
utm_type: opts.utm_type,
utm_source: opts.utm_source,
utm_medium: opts.utm_medium,
utm_term: opts.utm_term,
utm_content: opts.utm_content,
utm_campaign: opts.utm_campaign,
setting: this._getCookieOpt({
expires : 30
})
},opts || {}); if (conf.utm_type != 'null' && conf.utm_source != 'null') {
cookie('utm_type', parseInt(conf.utm_type), conf.setting);
cookie('utm_source', conf.utm_source, conf.setting);
cookie('utm_medium', conf.utm_medium, conf.setting);
cookie('utm_term', conf.utm_term, conf.setting);
cookie('utm_content', conf.utm_content, conf.setting);
cookie('utm_campaign', conf.utm_campaign, conf.setting);
} else {
return false;
}
},
navActive:function(uri){
var category = "",
pattern = /^http(s):\/\/.*\/.*\/(.*?)\/(.*?)\//g;
var mts = pattern.exec(uri);
if (mts != null)
{
var parent = mts[1];
var child = mts[2];
if (parent == 'aboutus'&& 'guidelinessecurityfriendlinks'.indexOf(child) < 0) {
category = parent + '>!gsf';
}
else{
category = parent + '>' + child;
}
} switch(category){
case 'aboutus>guidelines':
J('.navbar-nav li').removeClass('active');
J('.navbar-nav').children('li').eq(3).addClass('active');
break;
case 'aboutus>security':
J('.navbar-nav li').removeClass('active');
J('.navbar-nav').children('li').eq(2).addClass('active');
break;
case 'aboutus>friendlinks':
J('.navbar-nav li').removeClass('active');
break;
case 'aboutus>!gsf'://!guidelines!security!friendlinks
J('.navbar-nav li').removeClass('active');
J('#header .nav').children('li').eq(4).find('.dropdown-menu').remove();
J('.navbar-nav').children('li').eq(4).addClass('active');
break;
default:
J('.navbar-nav li').removeClass('active');
J('.navbar-nav').children('li').eq(1).addClass('active')
break;
}
}
};
return MOD;
});
define.pack("./main", ["jquery","./request","./template","./browser","./domains", "./cookie", "./html", "./log", "./error", "./helper", "./response"], function(require, exports, module) {
var J = require("jquery"),
Module = module.constructor;
var DD = window.DD || {};
DD.$ = DD.J = J;
DD.UI = DD.UI || {};
DD.Module = DD.Module || {};
DD.request=require("./request");
DD.template = require("./template");
DD.browser = require("./browser");
DD.domains = require("./domains");
DD.cookie = require("./cookie");
DD.html = require("./html");
DD.log = require("./log");
DD.error = require("./error");
DD.helper = require("./helper");
DD.response = require("./response");
DD.json = require("./json");
DD.user = require("./user");
return DD;
});

2. package/data.js (数据入口文件)

 /**
* 数据入口文件 v20151022
*/
define(['dd','common/config/url'],function(require){
var DD = require('dd'),
url = require('common/config/url');
var MOD = {
cmsAC:function(conf){
conf = conf || {};
DD.request.get({
url: url.cmsAC,
callback: {
success: conf.success //TODO:cache
}
});
},
cmsMR:function(conf){
conf = conf || {};
DD.request.get({
url: url.cmsMR,
callback: {
success: conf.success //TODO:cache
}
});
},
getFPAndInv:function(conf){
conf = conf || {};
DD.request.get({
url: url.getFPAndInv,
callback: {
success: conf.success //TODO:cache
}
});
},
logout:function(conf){
conf = conf || {};
DD.request.get({
url: url.logout,
callback: {
success: conf.success //TODO:cache
}
});
},
uinfo:function(conf){
conf = conf || {};
DD.request.get({
url: url.uinfo,
callback: {
success: conf.success //TODO:cache
}
});
}
};
return MOD;
});

   3. template/tmpl_index.js (页面模板文件)

 /** template|index|v20151027*/
define(['package/main','common/util/utils'], function(require, exports, module) {
var DD = require("package/main"),
util = require("common/util/utils");
var tmpl = {
'notice_tmpl': function(data) {
var __p = [],
_p = function(s) {
__p.push(s)
};
with(data || {}) {
var list = data.arcitleList;
var len = list.length;
if (len > 3) {
len = 3;
}
for (var i = 0; i < len; i++) {
var ntitle = DD.html.htmlEncode(list[i].title).replace(/[ ]/g,"");
if (ntitle.length <= 0) continue;
__p.push('<li><a title="');
_p(ntitle.replace('<br>', ''));
__p.push('" target=blank href="');
_p(DD.domains.base);
__p.push('/cms/arcitleDetail?id=');
_p(list[i].id);
__p.push('&cateId=3">');
_p(list[i].title.replace('<br>', '')+'</a>');
if (list[i].isNew) {
__p.push('<i clannouncementListass="new-icon"></i>');
}
__p.push('<span>');
_p(util.date.format(list[i].createTime,'yyyy-MM-dd'));
__p.push('</span></li>');
}
}
return __p.join("");
},
'media_tmpl': function(data) {
var __p = [],
_p = function(s) {
__p.push(s)
};
with(data || {}) {
var list = data.arcitleList;
var len = (list.length >= 6) ? 6 : list.length;
for (var i = 0; i < len; i++) {
var ntitle = DD.html.htmlEncode(list[i].title).replace(/[ ]/g,"");
var titleSub = "";
if (ntitle.length > 28) {
titleSub = ntitle.substr(0, 28) + "…"
} else {
titleSub = ntitle
}
__p.push('<li><a title="');
_p(ntitle.replace('<br>', ''));
__p.push('" target=blank href="');
_p(DD.domains.base);
__p.push('/cms/arcitleDetail?id=');
_p(list[i].id);
__p.push('&cateId=4">');
_p(titleSub.replace('<br>', ''));
__p.push('</a></li>');
}
}
return __p.join("");
},
'invest_list_tmpl': function(data) {
var __p = [],
_p = function(s) {
__p.push(s)
};
with(data || {}) {
var list_bw=data.list_borrows;
var len=list_bw.length;
var repayType=["还款方式","等额本息","先息后本","本息一次","等额平息"];
if (len > 5){
len = 5;
}
for(var i = 0; i < len; i++){
__p.push('<li id="tl00');
_p(i);
__p.push('" class="hvr-sweep-to-top">');
if(list_bw[i].isNew==1){
__p.push('<div class="i_01 new"></div>');
}
else{
__p.push('<div class="i_01"></div>');
}
__p.push('<div class="i_02"><img src="');
_p(list_bw[i].img);
__p.push('" style="width:36px;height:30px;margin:0 15px 0 -52px;"><a href="');
_p(DD.domains.base);
__p.push('/invest/prodetail_index?id=');
_p(list_bw[i].id);
__p.push('">');
_p(list_bw[i].no);
__p.push('</a></div>');
var num1=Number(list_bw[i].apr*100).toFixed(2);
__p.push('<div class="i_03">');
_p(num1);
__p.push('%</div>');
var dateName="";
if(list_bw[i].isDayLoan==1){
dateName="天"
}else{
dateName="个月"
}
__p.push('<div class="i_04">');
_p(list_bw[i].periods);
_p(dateName);
__p.push('</div><div class="i_05">');
_p(repayType[list_bw[i].repayType]);
var amountForm=DD.helper.toThousands(list_bw[i].amount);
__p.push('</div><div class="i_06">');
_p(amountForm);
__p.push('元</div><div class="i_07"><div class="index-progress" style="height: 46px;line-height: 45px;">');
_p(list_bw[i].process);
__p.push('%</div></div>');
var invaFlagStr=util.business.getInvesFlag(list_bw[i],"1");
__p.push('<div class="i_08"><a href="');
_p(DD.domains.base);
__p.push('/invest/prodetail_index?id=');
_p(list_bw[i].id);
if(list_bw[i].status == 2){
__p.push('" class="disableFla">');
}
else{
__p.push('">');
}
_p(invaFlagStr);
__p.push('</a></div>');
}
}
return __p.join("");
},
'financial_plans_tmpl': function(data) {
data = data ||{}
var __p = [],timeId=data.id+"1",num1="",
_p = function(s) {
__p.push(s)
};
__p.push('<p class="title">');
_p(data.name);
__p.push('</p>');
if(data.isNew == 1){
__p.push('<em class="new-icon"></em>');
}
if (!(data.addRate == undefined || data.addRate <= 0)) {
__p.push('<span class="perc" style="position: absolute;top: 63px;left: 162px;font-size: 18px;">+');
_p(Number(data.addRate).toFixed(1));
__p.push('%</span>');
num1=Number(data.num-data.addRate).toFixed(1);
}else{
num1=Number(data.num).toFixed(1);
}
__p.push('<span class="num">');
_p(num1);
__p.push('</span><span class="perc">%</span><p class="rev">预期年化收益</p>');
if(data.isShowTime){
__p.push('<a class="ableFla" href="');
}else{
__p.push('<a class="disableFla" href="');
}
_p(DD.domains.base);_p(data.toPage);__p.push('?id=');
_p(data.id);__p.push('">');_p(data.flagStr);__p.push('</a>');
if(data.isShowTime){
__p.push('<p class="time">剩余时间:<span id="');
_p(timeId);
__p.push('></span></p>');
}else{
__p.push('<p class="notime"> </p>');
}
return __p.join("");
} };
return tmpl;
});

4. module/init.js (模块业务文件)

 /*首页模块2|v2015-10-11*/
(function() {
var mods = [],
version = parseFloat(seajs.version);
define(['jquery','dd','common/plugin/slides.min','template/tmpl_index','package/data','common/util/utils'],function(require, exports, module) {
var uri = module.uri || module.id,
m = uri.split("?")[0].match(/^(.+\/)([^\/]*?)(?:\.js)?.J/i),
root = m && m[1],
name = m && "./" + m[2].substring(0,m[2].length),
i = 0,
len = mods.length,
curr, args, undefined;
name = name.replace(/\.r[0-9]{15}/, "");
for (; i < len; i++) {
args = mods[i];
if (typeof args[0] === "string") {
name === args[0] && (curr = args[2]);
args[0] = root + args[0].replace("./", "");
version > 1 && define.apply(this, args);
}
}
mods = [];
require.get = require;
return typeof curr === "function" ? curr.apply(this, arguments) : require;
});
define.pack = function() {
mods.push(arguments);
version > 1 || define.apply(null, arguments)
}
})();
define.pack("./animate",["jquery",'common/plugin/slides.min','dd'],function(require, exports, module){
var J = require('jquery'),
animate = {},
DD = require('dd');
require('common/plugin/slides.min')(J);
animate.slider = function(opt){
var conf = J.extend({
container : opt.container,
auto : opt.auto || true,
nav : opt.nav || true,
pause: opt.pause || true,
speed : opt.speed || 300,
pager : opt.pager || true
}, opt || {});
J(conf.container).responsiveSlides({
auto : conf.auto,
nav : conf.nav,
pause: conf.pause,
speed : conf.speed,
pager : conf.pager
});
}; animate.announcement = function(opt){
var conf = J.extend({
container : opt.container,
_interval : opt.interval || 3000,
speed : opt.speed || 600,
}, opt || {}),_moving,
_wrap = J(opt.container);
_wrap.hover(function(){
clearInterval(_moving);
},function(){
_moving = setInterval(function(){
var _field = _wrap.find("li:first");
var _h = _field.height();
_field.animate({marginTop:-_h+'px'},conf.speed,function(){
_field.css('marginTop',0).appendTo(_wrap);
})
},conf._interval)
}).trigger('mouseleave');
}; animate.bind = function(){
//animatedcss类动画的初始定义,ie8不加载
if(DD.browser.isIE(8)){ //判断是否是IE/
J(".callbacks1_s2").on('click',function(event){
J(event).addClass("callbacks_here");
});
}
J('#financial .plans').on({
'mouseover':function(){J(this).find('.time').show();},
'mouseout':function(){J(this).find('.time').hide();}
});
J('li.dropdown').on({
'mouseover':function(){J(this).addClass('open');},
'mouseout':function(){J(this).removeClass('open');}
}); J('#userInfoBox').on({
'mouseover':function(){J("#homelogin").addClass('open');},
'mouseout':function(){J("#homelogin").removeClass('open');}
}); J("#goInvest,#goAboutus,#_userName").on('click',function(){
window.location.href=J(this).attr("href");
});
}; animate.run = function(opts){
animate.slider({container : opts[0]});
animate.announcement({container : opts[1]});
animate.bind();
}; return animate;
});
define.pack("./render",["jquery",'dd','template/tmpl_index','package/data','common/util/utils'],function(require, exports, module){
var J = require('jquery'),
indexTmpl = require('template/tmpl_index'),
util = require("common/util/utils"),
data = require('package/data'),
DD = require('dd');
return {
ac: function(dom){
data.cmsAC({
success:function(data){
var obj = DD.response(data);
var opts = {
container: dom,
tmpl: indexTmpl.notice_tmpl(DD.json.isJSON(obj) ? obj: {}),
options: {}
};
DD.template.render(opts);
}});
},
mr: function(dom){
data.cmsMR({
success:function(data){
var obj = DD.response(data);
var opts = {
container: dom,
tmpl: indexTmpl.media_tmpl(DD.json.isJSON(obj) ? obj : {}),
options: {}
};
DD.template.render(opts);
}});
},
_invList: function(dom){
data.getFPAndInv({
success:function(data){
var obj = DD.response(data);
var opts = {
container: dom,
tmpl: indexTmpl.invest_list_tmpl(DD.json.isJSON(obj) ? obj : {}),
options: {}
};
DD.template.render(opts);
}});
},
_loadImg: function(dom){
dom = dom instanceof jQuery ? dom : J(dom);
data.getFPAndInv({
success:function(data){
var obj = DD.response(data);
obj=DD.json.isJSON(obj) ? obj : {};
for (i = 0; i < 5; i++) {
util.business.loadImg(obj.list_borrows[i].process,dom);
}
}});
},
_finPlan:{
bind:function(type,obj){
if(obj && ("" != obj) && ("undifinde" != obj)){
var conf = {
num: obj.apr * 100,
flagStr: util.business.getInvesFlag(obj,"0"),
id: obj.id,
isNew: obj.isNew,
isShowTime: obj.status == 2 ? true : false,
addRate: obj.addRate * 100
};
switch (type) {
case 0:
conf = J.extend({
name: '活期宝',
toPage: '/invest/flex_borrow',
container: '#huoqibao'
},conf);
break;
case 1:
conf = J.extend({
name: '3个月计划',
toPage: '/invest/optimise_borrow',
container: '#3yue'
},conf);
break;
case 2:
conf = J.extend({
name: '6个月计划',
toPage: '/invest/optimise_borrow',
container: '#6yue'
},conf);
break;
case 3:
conf = J.extend({
name: '12个月计划',
toPage: '/invest/optimise_borrow',
container: '#12yue'
},conf);
break;
default:
return false;
}
var opts = {
container: conf.container,
tmpl: indexTmpl.financial_plans_tmpl(conf),
options: {}
};
J(opts.container).addClass("sa_top");
DD.template.render(opts);
}
},
show:function(){
var self = this;
data.getFPAndInv({
success:function(data){
var obj = DD.response(data);
obj = DD.json.isJSON(obj) ? obj : {};
self.bind(0,obj.flex_borrows[0]);
self.bind(1,obj.optimise1_borrows[0]);
self.bind(2,obj.optimise2_borrows[0]);
self.bind(3,obj.optimise3_borrows[0]);
}});
}
},
run:function(opts){
this.ac(opts[0]);
this.mr(opts[1]);
this._finPlan.show();
this._invList(opts[2]);
this._loadImg(opts[3]);
}
}; });
define.pack("./init",["jquery",'dd','common/util/utils'],function(require, exports, module){
var J = require('jquery'),
util = require("common/util/utils"),
DD = require('dd');
return {
init: function(options){
var that = this;
var opts = J.extend({
_amOpt: ['#slider','ul.announcements'],
_rdOpt: ['.announcements','#mediaReports','#investmentList','#tl000 .index-progress']
}, options);
require.async('./animate', function(animate) {
animate.run(opts._amOpt);
});
require.async('./render', function(render) {
render.run(opts._rdOpt);
});
},
time: util.business.showBorrowTime
};
});

5. common/event.js (事件处理文件)

注:这里代码主要是自定义事件的,个人感觉JQuery封装的事件挺强大的,所以暂未使用,后期有好的思路需要重新写下

 /**
* 事件处理 v20151027
*/
define(['lib/jquery'],function(require, exports, module) {
var $ = require('lib/jquery');
exports.batchBind = function(dom, obj) {
for (var evt in obj) {
(function(evt, handlers) {
$(dom).bind(evt, function(e) {
var e = e || event;
var target = e
.target || e.srcElement;
for (var cls in handlers) {
if ($(target).hasClass(cls)) {
if (handlers[cls].call(target)) {
break;
}
}
}
});
})(evt, obj[evt]);
}
};
exports.enableCustomEvent = function(obj) {
$.extend(obj, {
addEvent: function(type, func) {
this._customEventListeners = this._customEventListeners || {};
this._customEventListeners[type] = this._customEventListeners[type] || [];
this._customEventListeners[type].push(func);
return this;
},
delEvent: function(type, func) {
var funcs = this._customEventListeners[type];
if (funcs) {
for (var i = funcs.length - 1; i >= 0; i--) {
if (funcs[i] == func) {
funcs[i] = null;
break;
}
}
}
return this;
},
fireEvent: function(type) {
if (!this._customEventListeners || !this._customEventListeners[type]) return;
var funcs = this._customEventListeners[type],
args = $.makeArray(arguments),
tmp = null,
returnValue = true;
args.shift();
for (var i = 0, j = funcs.length; i < j; i++) {
if (funcs[i]) {
try {
tmp = funcs[i].apply(this, args);
if (tmp === false) {
returnValue = false;
}
} catch (ox) {}
}
}
return returnValue;
}
});
return obj;
};
});

6. ui/dialog.js (UI组件-弹窗 )

     注:首页中未使用,需要根据网站弹窗样式功能修改

 /**UI|Dialog|v20151029**/
define("./dialog",["jquery","dd"],function(require, exports, module) {
var J = require('jquery'),
DD = require('dd');
//require('./dialog.css'); //css
var jQuery, $;
jQuery = $ = J;
var _id = 0;
var Dialog = function(options) {
this.id = 'dialog_' + (++_id);
this.dom = null;
this.mask = null;
this.timer = null;
this.options = J.extend({
title: options.title || '',
header: options.header || '',
footer: options.footer || '',
content: options.content || '',
submitButtonText: options.submitButtonText || '确定',
cancelButtonText: options.cancelButtonText || '取消',
dragable: options.dragable || true, //是否可以拖曳
destroyWhenClosed: options.destroyWhenClosed || true,
autoClose: options.autoClose || false,
autoCloseDelay: options.autoCloseDelay || 1500,
useModal: options.useModal || true,
closeAfterSubmit: options.closeAfterSubmit || true,
showCloseButton: options.showCloseButton || true,
showSubmitButton: options.showSubmitButton || true,
showCancelButton: options.showCancelButton || true,
showHeader: options.showHeader || true,
showFooter: options.showFooter || true,
onCreated: options.onCreated || null,
onOpened: options.onOpened || null,
onClosed: options.onClosed || null,
onDestroyed: options.onDestroyed || null,
onSubmitted: options.onSubmitted || null,
onCanceled: options.onCanceled || null,
realOnCanceled: options.realOnCanceled || null,
width: options.width || '350px',
height: options.height || 'auto',
zIndex: options.zIndex || 5000,
template: options.template || '',
autoPosit: options.autoPosit || true,
left: options.left || '25%',
top: options.top || '25%'
}, options || {});
Dialog.instances[this.id] = this;
}
Dialog.prototype = {
create: function() {
var _this = this;
var tplData = {};
tplData.id = this.id;
tplData.showHeader = this.options.showHeader ? '' : 'display:none;';
tplData.showFooter = this.options.showFooter ? '' : 'display:none;';
tplData.showCloseButton = this.options.showCloseButton ? '' : 'display:none;';
tplData.showSubmitButton = this.options.showSubmitButton ? '' : 'display:none;';
tplData.showCancelButton = this.options.showCancelButton ? '' : 'display:none;';
tplData.header = this.options.header ? this.options.header : '';
tplData.title = this.options.title ? this.options.title : '';
tplData.footer = this.options.footer ? this.options.footer : '';
tplData.content = this.options.content ? this.options.content : '';
tplData = J.extend(this.options, tplData);
var dialog = DD.template.parse(this.options.template, tplData);
J(document.body).append(dialog);
if ($.browser.msie && !window.XMLHttpRequest) {
var divHeight = J('#' + this.id).height();
$('#' + this.id).find(' > iframe').height(divHeight);
}
this.dom = J('#' + this.id).get(0);
J('#' + this.id + '_close').click(function() {
_this.options.onCanceled.call(_this);
_this.close();
});
J('#' + this.id + '_submit').click(function() {
if (_this.options.onSubmitted.call(_this) || _this.options.closeAfterSubmit) {
_this.close();
}
});
J('#' + this.id + '_cancel').click(function() {
_this.options.onCanceled.call(_this);
_this.options.realOnCanceled.call(this);
_this.close();
});
if (this.options.dragable) {}
if (this.options.useModal) {
this.mask = new Dialog.Mask({
zIndex: this.options.zIndex - 1,
target: this.options.maskTarget
});
this.mask.create();
}
J('#' + this.id + ',#' + this.id + '_submit,#' + this.id + '_cancel,#' + this.id + '_close').attr('tabindex', 0);
this.options.onCreated.call(this);
},
open: function() {
if (this.dom == null) {
this.create();
}
if (this.options.autoPosit) {
var topPos = J(document).scrollTop() || 0,
win = window;
try {
while (win.frameElement) {
topPos += J(win.parent.document).scrollTop() || 0;
if (win.parent.$e) {
topPos -= win.parent.$e(win.frameElement).getXY()[1];
} else if (win.parent.J) {
topPos -= win.parent.J(win.frameElement).offset().top;
} else {
break;
}
win = win.parent;
}
} catch (e) {
topPos = J(document).scrollTop() || 0, win = window;
}
if (this.options.vCenter) {
topPos = J(document).scrollTop() || 0 + ($(window).height() - $(this.dom).height()) / 2;
}
if (topPos < 0) {
topPos = 0;
}
J(this.dom).css({
left: Math.floor((J(window).width() - J(this.dom).width()) / 2) + 'px',
top: this.options.vCenter ? topPos : 100 + topPos + 'px'
});
}
J(this.dom).show().focus();
var _this = this;
if (this.options.autoClose) {
if (this.timer) {
clearTimeout(this
.timer);
}
this.timer = setTimeout(function() {
_this.close();
}, this.options.autoCloseDelay);
}
if (this.mask) {
this.mask.show();
}
this.options.onOpened.call(this);
},
close: function() {
J(this.dom).hide();
if (this.mask) {
this.mask.hide();
}
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
if (this.options && this.options.onClosed) {
this.options.onClosed.call(this);
}
if (this.options && this.options.destroyWhenClosed) {
var _this = this;
setTimeout(function() {
_this.destroy();
}, 10);
}
},
resize: function(size, resizeContent) {
if (resizeContent) {
var target = J('div.pop-common-bd', this
.dom);
} else {
var target = J(this.dom);
}
if (size.width) {
target.css({
'width': size.width
});
}
if (size.height) {
target.css({
'height': size.height
})
}
},
changeButtonText: function(type, text) {
switch (type) {
case 'submit':
var btn = J('#' + this.id + '_submit').get(0);
break;
case 'cancel':
var btn = J('#' + this.id + '_cancel').get(0);
break;
}
btn.innerHTML = text;
},
destroy: function() {
try {
J(this.dom).find('iframe').remove();
J(this.dom).remove();
if (this.mask) {
this.mask.destroy();
}
this.options.onDestroyed.call(this);
this.dom = null;
this.options = null;
Dialog.instances[this.id] = null;
delete
Dialog.instances[this.id];
} catch (ex) {}
}
};
Dialog.template = ['<div id="<%=id%>" class="<%=mainStyle%>" style="position: absolute; z-index: <%=zIndex%>; top: <%=top%>; left: <%=left%>; height: <%=height%>; width: <%=width%>; display:none;">',
'<div class="py-pop-inner">', '<div class="pop-hd" id="<%=id%>_header" style="<%=showHeader%>" >', '<h3><%=title%></h3>', '</div>', '<div class="pop-bd"><%=content%></div>',
'<div class="pop-ft" id="<%=id%>_footer" style="<%=showFooter%>"><%=footer%><div class="pop-cmds"><a class="btn btn-green" style="<%=showSubmitButton%>" id="<%=id%>_submit" title="<%=submitButtonText%>"><b class="button"><span class="b-txt"><%=submitButtonText%></span></b></a><a title="<%=cancelButtonText%>" class="btn" style="<%=showCancelButton%>" id="<%=id%>_cancel"><b class="button"><span class="b-txt"><%=cancelButtonText%></span></b></a></div></div>',
'</div>', '<a id="<%=id%>_close" title="关闭对话框" href="#" class="close" style="<%=showCloseButton%>" onclick="return false;"><i class="icon i-pop-close"></i></a>',
'<iframe style="width: <%=width%>;" tabindex="-1" class="shade-ie6" frameborder="0" src="about:blank" scrolling="no"></iframe>', '</div>'].join('');
Dialog.instances = {};
Dialog.close = function(id) {
if (id) {
Dialog.instances[id].close();
} else {
for (var ins in Dialog.instances) {
Dialog.instances[ins].close();
}
}
}
Dialog.destroy = function() {
for (var ins in Dialog.instances) {
try {
Dialog.instances[ins].destroy();
} catch (ex) {}
}
Dialog.instances = null;
}
Dialog.Mask = function(options) {
this.options = J.extend({
target: window,
zIndex: 990,
opacity: 0
}, options || {});
this.dom = null;
}
Dialog.Mask.prototype = {
create: function() {
var offset = this.getOffset();
var width = J(this.options.target).width(),
height = J(this.options.target).height(),
zIndex = this.options.zIndex,
opacity = this.options.opacity;
this.dom = document.createElement('div');
document.body.appendChild(this.dom);
J(this.dom).css({
'position': 'absolute',
'zIndex': zIndex,
'left': offset.left + 'px',
'top': offset.top + 'px',
'width': width + 'px',
'height': height + 'px',
'display': 'none'
});
J(this.dom).append('<div style="position:absolute; width:' + width + 'px;height:' + height + 'px; background:#000000;z-index:' + zIndex + ';opacity:' + opacity
+ '; filter:alpha(opacity=' + (opacity * 100) + ');-moz-opacity:' + opacity + ';"></div>');
if (jQuery.browser.msie) {
J(this.dom).append('<iframe style="opacity:0; filter:alpha(opacity=0);-moz-opacity:0;" scrolling="No" style="" border="0" frameborder="0" width="' + width + '" height="' + height + '"></iframe>');
} else if (jQuery.browser.opera) {
J(this.dom).append('<img onmousedown="return false;" galleryimg="no" style="z-index:' + zIndex + '" width="' + width + '" height="' + height + '"/>');
}
},
show: function() {
if (!this.dom) {
this.create();
} else {
var offset = this.getOffset();
J(this.dom).css({
'left': offset.left + 'px',
'top': offset.top + 'px'
});
}
J(this.dom).show();
},
hide: function() {
J(this.dom).hide();
},
destroy: function() {
J(this.dom).remove();
this
.dom = null;
this.options = null;
},
getOffset: function() {
if (this.options.target == window || this.options.target == document) {
var offset = {
left: 0,
top: 0
};
} else {
var offset = J(this.options.target).offset();
}
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop || 0;
offset.top += scrollTop;
return
offset;
}
}
Dialog.create = function(options) {
var that = this;
var opts = J.extend({}, options);
switch (options.type) {
case 'warn':
opts.title = options.title ? options.title : '温馨提示';
opts.template = (Dialog.template || '').replace('<%=content%>', '<div class="xpy-media"><div class="img"><i class="ico-warn-20"></i></div><div class="txt ft-14"><%=content%></div></div>');
break;
case 'error':
case 'notice':
opts.autoClose = true;
opts.useModal = false;
if (J('select').size()) {
opts.useModal = true;
}
opts.template = '<div id="<%=id%>" style="z-index:<%=zIndex%>" class="hint hint-blue"><div class="hint-inner"><i class="ico-hint ico-busy"></i><span class="hint-txt"><%=content%></span></div></div>';
opts.content = options.content;
opts.zIndex = 9999;
break;
case 'verify':
options.content = options.content || '';
opts.closeAfterSubmit = false;
opts.content = '<div class="pop-vcode">\
<table>\
<tbody>\
<tr>\
<td colspan="2"><span class="pop-vcode-tips">' + (options.subTitle || '请输入验证码') + '</span> <br/>' + options.content + '</td>\
</tr>\
<tr>\
<td>验证码:</td>\
<td>\
<label accesskey="v"><input autocomplete="off" type="text" class="verifycode" name="verifycode_div" maxlength="6">不区分大小写</label>\
</td>\
</tr>\
<tr>\
<td></td>\
<td>\
<img height="53" width="130" src="http://' + (document.domain == 'qq.com' ? 'captcha.qq.com' : 'captcha.pengyou.com') + '/getimage?aid=15000901&' + Math.random() + '">\
<a href="#" class="js_change" tabindex="-1" onclick="">看不清,换一张</a>\
</td>\
</tr>\
</tbody>\
</table>\
</div>';
opts.onOpened = function() {
var jqInput = J('input.verifycode', this.dom),
jqChange = J('a.js_change', this.dom);
if (!this.dom) {
return false;
};
var dia = this;
jqInput.focus();
jqChange.click(function() {
var url = 'http://' + (document.domain == 'qq.com' ? 'captcha.qq.com' : 'captcha.pengyou.com') + '/getimage?aid=15000901&' + Math.random();
J(this).parent().find('img').attr('src', url);
jqInput.trigger('focus');
return false;
});
jqInput.unbind('keydown').bind('keydown', function(ev) {
var keycode = ev.keyCode,
subRS = false;
if (keycode === 13) {
ev.preventDefault();
subRS = opts.onSubmitted.call(dia);
if (subRS || options
.closeAfterSubmit) {
dia.close();
}
}
});
};
opts.onSubmitted = function() {
if (!this.dom) {
options.onSubmitted.call(this, '');
if (that && that.close) {
that.close();
} else {
Dialog.close();
}
return false;
};
var ipt = J('input.verifycode', this.dom),
code = ipt.val();
if (/^\s*$/.test(code)) {
alert('请输入验证码');
ipt.focus();
return false;
} else {
options.onSubmitted.call(this, code);
return true;
}
};
break;
case 'success':
opts.autoClose = true;
opts.useModal = false;
if (J('select').size()) {
opts.useModal = true;
}
opts.template = options.template;
opts.content = options.content;
opts.zIndex = 9999;
break;
}
return new Dialog(opts);
}
var DialogClass = {
open: function(type, content, config) {
var args = [].slice.apply(arguments);
config = args[args.length - 1];
if ($.isPlainObject(config)) {
args.splice(-1, 1);
} else {
config = null;
}
if (args.length > 1) {
type = args[0];
content = args[1];
} else if (args.length === 1) {
type = null;
content = args[0];
} else {
type = null;
content = '';
}
var confDef = {
type: '',
title: ''
},dialog;
config = config ? $.extend(confDef, config) : confDef;
config.content = config.content || content;
config.type = config.type || type;
dialog = Dialog.create(config);
dialog.open();
return dialog;
},
closeAll: function() {
Dialog.close();
},
create: Dialog.create,
manager: Dialog
};
return DialogClass;
});

7.index.jsp(页面文件-js部分)

 <script type="text/javascript">
;(function () {
var fn = function () {
seajs.use(['package/main','jquery'],function(d,$){
var href = window.location.href;
if(href&&href.indexOf('ddshenbian.com') > 0){
d.user.navActive(href);
}
d.user.toTop();
});
}; setTimeout(fn,0);
})();
</script>
setTimeout(function () {
seajs.use('package/main', function(d){
d.user.utm2cookie({
utm_type: '<%=utm_type%>',
utm_source: '<%=utm_source%>',
utm_medium: '<%=utm_medium%>',
utm_term: '<%=utm_term%>',
utm_content: '<%=utm_content%>',
utm_campaign: '<%=utm_campaign%>'
});
d.user.login();
d.user.logout();
});
},1000);
var target=[],time_id =[];
;(function () {
window.onload = function () {
seajs.use(['lib/jquery','package/main'],function () {
seajs.use('module/index/init',function (i) {
i.init();
setTimeout(function(){
i.time(target,time_id);
}, 100);
});
});
};
})();

下面看下页面效果:

【PC网站前端架构探讨系列】关于中小型PC网站前端架构方案的讨论与实践        【PC网站前端架构探讨系列】关于中小型PC网站前端架构方案的讨论与实践

存在问题

    1.最明显会带来的问题就是请求增多,kissy这一方面做的很好,大多数的解决办法是需要运维去服务器做相关配置来实现

    2.事件处理机制不太完善,目前还在学习中…

    3.缓存处理、页面渲染等有待完善,请大神多多赐教