案例1:
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title></title>
<script src="jquery-2.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
//定義一個controller
var pilicontroller = {
//選擇視圖
start: function () {
this.view.start();
},
//将使用者操作映射到模型更新上
set: function (name) {
this.model.setperson(name);
}
};
pilicontroller.model = {
//此資料從中間資料層拿json.data(經中間件(簡單做法封轉一個頁面所有的業務請求接口一個ajax請求回調搞定)批量查詢後的靜态資源)并處理填充
pilikv: {
'葉小钗': '刀狂劍癡',
'一頁書': '百世經綸',
'素還真': '清香白蓮'
curperson: null,
//資料模型負責業務邏輯和資料存儲
setperson: function (name) {
this.curperson = this.pilikv[name] ? name : null;
this.onchange();
//通知資料同步更新
onchange: function () {
pilicontroller.view.update();
//相應視圖對目前狀态的查詢
getpiliaction: function () {
return this.curperson ? this.pilikv[this.curperson] + this.curperson : '???';
//=======================================================================
// 以下為界面代碼,當要調整界面,改這裡就行啦~~~
pilicontroller.view = {
//使用者觸發change事件
$('#pili').change(this.onchange);
pilicontroller.set($('#pili').val());
update: function () {
$('#end').html(pilicontroller.model.getpiliaction());
pilicontroller.start();
});
</script>
</head>
<body>
<select id="pili">
<option value="葉小钗">葉小钗</option>
<option value="一頁書">一頁書</option>
<option value="素還真">素還真</option>
</select>
<div id="end"></div>
</body>
</html>
案例2
<!doctype html>
<html lang="en">
<meta charset="utf-8" />
<script>
$(function () {
var countries = function () { }
countries.prototype = {
_items: [],
_getdata: function (success) {
//此資料從中間資料層拿json.data(經中間件(簡單做法封轉一個頁面所有的業務請求接口一個ajax請求回調搞定)批量查詢後的靜态資源)并處理填充
var items = [
{ id: 0, name: '中國' },
{ id: 1, name: '日本' },
{ id: 2, name: '美國' }
];
$.extend(this._items, items);
success(items);
//events
on_selected: $.callbacks(),
on_inserted: $.callbacks(),
//methods
select: function () {
var self = this;
this._getdata(function (items) {
self.on_selected.fire({
sender: self,
items: items
});
});
insert: function (item) {
this._items.push(item);
self.on_inserted.fire({ sender: self, item: item });
}
var countries = new countries();
countries.on_selected.add(function (args) {
$(args.items).each(function () {
$('#countries').append($('<option>').attr('value', this.id).text(this.name));
});
});
countries.on_inserted.add(function (args) {
$('#countries').append($('<option selected="selected">').attr('value', args.item.id).text(args.item.name));
var id = 10;
$('#btnadd').click(function () {
countries.insert({ id: ++id, name: $('#countryname').val() });
countries.select();
<select id="countries"></select>
<div>
<input id="countryname" /><button id="btnadd">添加清單item</button>
</div>