1. 개방 분석
안녕하세요, 아직도 이전 기사를 기억하십니까? 주로 "탭"플러그인이 코드를 구성하고 구현하는 방법과 프로세스 디자인이 객체 지향적 사고 설계와 어떻게 결합되는지 알려줍니다.
플러그인을 설계하는 방법? 두 가지 방법은 서로의 강점과 약점으로부터 배울 수있는 고유 한 장점과 단점이 있습니다. 이 일련의 기사는 학습 지향적이며 모든 사람들이 특정 시나리오를 사용하는 방법을 결정합니다. 이 기사에서 우리는 여전히 "탭"인스턴스에 중점을 둡니다.
관련 기능을 계속 확장하십시오. 헤헤 헤 (Hehehe), 덜 말도 안되는 말을하고 요점에 도달하십시오. 실제 렌더링 직접 :
당신은 그것을 보았고 새로운 기능이 추가되었습니다. 초기화 할 때 모듈 구성 정보 항목의 항목 수가 우리가 지정한 것보다 크면 "더 많은 모듈"에 표시됩니다.
숨겨진 작동 항목 목록에서 초기화 매개 변수 구성도 초기화시 항목 수를 지정하기위한 추가 "DisplayMax"와 같은 추가 "displayMax"와 같은 항목 속성 "상태"와 같은 새로 조정되었습니다.
초기화 중에 구성이 필요하지 않습니다. 동적 구성은 프로그램에서 생성되어 프로그램 유연성을 증가시킵니다. 아래에서 자세히 분석 해 봅시다.
(ii), 사례 분석
(1) 먼저이 플러그인이하는 일을 결정하십시오. 플러그인의 통화 메소드와 구성 매개 변수 설명을 살펴 보겠습니다. 다음 코드 :
코드 사본은 다음과 같습니다.
{
ButtonText : "모듈 추가",
결과: [
{
텍스트 : "마법사 프롬프트",
URL : "help.html",
showclose : "0"
},
{
텍스트 : "학생 정보",
URL : "info.html",
showclose : "1"
},
{
텍스트 : "학생 분류",
URL : "category.html",
showclose : "1"
},
{
텍스트 : "Big Bear {{bb}}",
URL : "bb.html",
showclose : "1"
},
{
텍스트 : "베타 테스트 모듈",
URL : "test.html",
showclose : "1"
},
{
텍스트 : "세 명의 지방 남자",
URL : "help.html",
showclose : "1"
},
{
텍스트 : "네 대머리 남자",
URL : "help.html",
showclose : "1"
}
],,
DisplayMax : 5 // 최대 디스플레이 항목
}
"bigbear.ui.createtab"에는 두 개의 매개 변수가 포함되어 있습니다. 첫 번째는 dom 노드 객체이고 두 번째는 플러그인 매개 변수 옵션입니다. "ButtonText"는 "탭"플러그인의 작업 버튼에 대한 텍스트 설명을 나타냅니다.
"결과"는 텍스트 설명을 포함하여 탭 항목의 속성을 포함하는 배열입니다. 탭 항목을 클릭 할 때 요청하는 데 사용되는 URL은 "showclose"는 탭 옵션이 닫기 버튼을 표시하는지 여부를 나타냅니다.
초기화 중에 "상태"도 제거되며 구성이 필요하지 않으며 구성이 프로그램에서 동적으로 생성됩니다. 닫힌 상태가있을 수 있으며, 이는 1-Default Display, 0-Off 상태 및 기본 항목 번호보다 2-로 표시됩니다.
(2) 기능은 단계로 도입됩니다
1 ---, 선택적 매개 변수를 통해 플러그인을 초기화하십시오.
코드 사본은 다음과 같습니다.
$ (function () {
bigbear.ui.createtab ($ ( "#tab"), {
ButtonText : "모듈 추가",
결과: [
{
텍스트 : "마법사 프롬프트",
URL : "help.html",
showclose : "0"
},
{
텍스트 : "학생 정보",
URL : "info.html",
showclose : "1"
},
{
텍스트 : "학생 분류",
URL : "category.html",
showclose : "1"
},
{
텍스트 : "Big Bear {{bb}}",
URL : "bb.html",
showclose : "1"
},
{
텍스트 : "베타 테스트 모듈",
URL : "test.html",
showclose : "1"
},
{
텍스트 : "세 명의 지방 남자",
URL : "help.html",
showclose : "1"
},
{
텍스트 : "네 대머리 남자",
URL : "help.html",
showclose : "1"
}
],,
DisplayMax : 5 // 최대 디스플레이 항목
});
});
2 ---, 초기화 중 항목 수 검증과 같은 시간 바인딩 및 관련 비즈니스 로직 렌더링 및 완전한 시간.
코드 사본은 다음과 같습니다.
tabproto.init = function () {
if (this._isemptyresult ()) {
this._setContent ( "아직 모듈 없음!");
}
var that = this;
this.getElem (). find ( ". title .adder")
.Text ( " +" + this.getOpts () [ "ButtonText"]))
.on ( "클릭", function () {
that.getelem (). find ( ". console-panel"). slidetoggle (function () {
that._renderconsolepanel ( "0");
});
});
$ .Each (this.getOpts () [ "result"], function (i, item) {
if (that._isdisplaymax (i + 1)) {
that._saveorupdatestatus (항목, "1");
}
또 다른{
that._saveorupdatestatus (항목, "2");
}
that._render (항목);
});
if (! that._isdisplaymax (this.getOpts () [ "result"]. length)) {
this.getElem (). find ( ". title .more-mod"). fadein (function () {
$ (this) .find ( ". tag"). on ( "click", function () {
var root = $ (this) .next ();
root.empty ();
$ .Each (that._getItemListByStatus ( "2"), 함수 (i, data) {
$ ( "<div> </div>"). Text (data [ "text"])
.on ( "클릭", function () {
if (that._getItemListByStatus ( "1"). length <that.getOpts () [ "displayMax") {
that.getelem (). find ( ". title .items div"). eq (data [ "index"]). fadein (function () {
that._saveorupdatestatus (data, "1");
});
}
또 다른{
ALERT ( "모듈이 추가 될 수 없으며 현재 최대 숫자입니다!");
}
})
.appendto (루트);
});
root.toggle ();
});
});
}
this.getElem (). find ( ". title .items div")
.eq (0)
.Trigger ( "클릭"); // 하나가 있어야한다고 가정합니다. 그렇지 않으면 플러그인이 의미가 없습니다!
};
3 ---, 탭 전환 및 데이터 컨텐츠 렌더링 작업.
코드 사본은 다음과 같습니다.
tabproto._setCurrent = function (index) {
var items = this.getElem (). find ( ". title .items div"). removeClass ( "active");
items.eq (index) .addclass ( "active");
var contents = this.getElem (). find ( ". content .c"). hide ();
contents.eq (index) .show ();
};
코드 사본은 다음과 같습니다.
item.on ( "클릭", function () {
that._setCurrent ($ (this) .index ());
that._getContent (data [ "url"]). done (function (result) {
that._setContent (결과);
})
.fail (function () {
새 오류를 던지십시오 ( "순 오류!");
});
})
코드 사본은 다음과 같습니다.
tabproto._setContent = function (html) {
this.getElem (). find ( ". content"). html (html);
};
tabproto._getContent = function (url) {
return $ .ajax ({
URL : URL
});
};
4 ---, 핵심 보조 데이터 운영 방법에는 DOM이 포함되지 않습니다.
코드 사본은 다음과 같습니다.
/ * 업데이트 시간 2015 1/26 15:36 */
tabproto._isdisplaymax = function (size) {
var displaymax = this.getOpts () [ "displayMax"] || 5;
return (size <= displaymax)? 사실 : 거짓;
};
tabproto._isemptyresult = function () {
if (! this.getOpts () [ "result"]. length) {
거짓을 반환합니다.
}
진실을 반환하십시오.
};
tabproto._saveorupdatestatus = 함수 (항목, 상태) {
항목 [ "상태"] = 상태;
};
tabproto._getItemListByStatus = function (status) {
var list = [];
var result = this.getOpts () [ "결과"];
$ .Each (result, function (i, item) {
if (status == item [ "status"]) {
list.push (항목);
}
});
반환 목록;
};
tabproto._getStatusByIndex = function (index) {
var status = null;
var result = this.getOpts () [ "결과"];
$ .Each (result, function (i, item) {
if (index == item [ "index"]) {
상태 = 항목 [ "상태"];
}
});
반환 상태;
};
(iii), 학습을위한 완전한 코드 ,이 코드는 디렉토리 구조 및 관련 파일을 포함하여 테스트되었습니다.
1, HTML
코드 사본은 다음과 같습니다.
<body>
<div>
빅 베어 {{bb}}-dxj ui ------ 탭
</div>
<div>
<div id = "탭">
<div>
<div>
+ 학생 정보 추가
</div>
<div>
<!-<div> <span> x </span> 환영 페이지 </div>
<div> <span> x </span> 사용자 관리 </div>
<div> <span> x </span> bigbear </div>->
</div>
<div>
<div> 더 많은 모듈 </div>
<div>
</div>
</div>
</div>
<div>
</div>
<div>
<!-<div>
<div> <span> 이름 : </span> <입력 유형 = "text"/> </div>
<div> <span> 참고 : </span> <textarea> </textarea> </div>
</div> <div> <입력 유형 = "버튼"값 = "저장"/> </div>
->
</div>
</div>
</div>
</body>
2, CSS
코드 사본은 다음과 같습니다.
.dxj-ui-hd {
패딩 : 0px;
여백 : 0 Auto;
마진 탑 : 30px;
너비 : 780px;
높이 : 60px;
라인 높이 : 60px;
배경 : #3385ff;
색상 : #ffff;
Font-Family : "Microsoft Yahei";
글꼴 크기 : 28px;
텍스트 정렬 : 센터;
글꼴 중량 : 대담한;
}
.dxj-ui-bd {
패딩 : 0px;
여백 : 0 Auto;
너비 : 778px;
패딩 탑 : 30px;
패딩 바닥 : 30px;
오버플로 : 숨겨진;
테두리 : 1px 고체 #3385ff;
}
.dxj-ui-bd #tab {
패딩 : 0px;
여백 : 0 Auto;
너비 : 720px;
오버플로 : 숨겨진;
위치 : 상대;
}
.dxj-ui-bd #tab .title {
너비 : 720px;
오버플로 : 숨겨진;
국경 바닥 : 2px 고체 #3385ff;
}
.dxj-ui-bd #tab .title .adder {
너비 : 160px;
높이 : 32px;
라인 높이 : 32px;
배경 : #DC143C;
색상 : #ffff;
Font-Family : "Microsoft Yahei";
글꼴 크기 : 14px;
텍스트 정렬 : 센터;
글꼴 중량 : 대담한;
플로트 : 왼쪽;
커서 : 포인터;
}
.dxj-ui-bd #tab .title .more-mod {
오버플로 : 숨겨진;
테두리 : 1px 고체 #dc143c;
너비 : 70px;
위치 : 절대;
오른쪽 : 0;
마진 오른쪽 : 6px;
디스플레이 : 없음;
}
.dxj-ui-bd #tab .title .more-mod .tag {
높이 : 32px;
라인 높이 : 32px;
너비 : 70px;
배경 : #DC143C;
색상 : #ffff;
글꼴 패밀리 : arial;
글꼴 크기 : 12px;
텍스트 정렬 : 센터;
커서 : 포인터;
}
.dxj-ui-bd #tab .title .more-mod .mods {
오버플로 : 숨겨진;
너비 : 70px;
디스플레이 : 없음;
}
.dxj-ui-bd #tab .title .more-mod .mods div {
높이 : 24px;
라인 높이 : 24px;
너비 : 62px;
글꼴 패밀리 : arial;
글꼴 크기 : 12px;
커서 : 포인터;
왼쪽 패딩 : 10px;
}
.dxj-ui-bd #tab .title .items {
높이 : 32px;
너비 : 480px;
오버플로 : 숨겨진;
플로트 : 왼쪽;
}
.dxj-ui-bd #tab .title .items div {
패딩 : 0px;
마진 왼쪽 : 10px;
너비 : 84px;
높이 : 32px;
라인 높이 : 32px;
배경 : #3385ff;
색상 : #ffff;
글꼴 패밀리 : arial;
글꼴 크기 : 12px;
텍스트 정렬 : 센터;
위치 : 상대;
플로트 : 왼쪽;
커서 : 포인터;
}
.dxj-ui-bd #tab .title .items div span.del {
너비 : 16px;
높이 : 16px;
라인 높이 : 16px;
디스플레이 : 블록;
배경 : #DC143C;
위치 : 절대;
오른쪽 : 0;
상단 : 0;
커서 : 포인터;
}
.dxj-ui-bd #tab .content {
너비 : 716px;
패딩 탑 : 30px;
오버플로 : 숨겨진;
테두리 : 2px 고체 #3385ff;
테두리 탑 : 0px;
Min-Height : 130px;
텍스트 정렬 : 센터;
}
.dxj-ui-bd #tab .content 테이블 {
여백 : 0 Auto;
}
.dxj-ui-bd #tab .content div.c {
패딩 탑 : 20px;
왼쪽 패딩 : 20px;
배경 : #eee;
높이 : 140px;
}
.dxj-ui-bd #tab .content div.c .input-content {
마진-탑 : 10px;
글꼴 패밀리 : arial;
글꼴 크기 : 12px;
}
.dxj-ui-bd #tab .console-panel {
너비 : 716px;
패딩 탑 : 20px;
패딩 바닥 : 20px;
오버플로 : 숨겨진;
테두리 : 2px 고체 #3385ff;
테두리 탑 : 0px;
국경 바닥 : 2px 고체 #3385ff;
배경 : #fff;
디스플레이 : 없음;
}
.활동적인 {
글꼴 중량 : 대담한;
}
3, bigbear.js
코드 사본은 다음과 같습니다.
(기능 ($) {
var win = 창;
var bb = win.bigbear = win.bigbear || {
UI : {}
};
var ui = bb.ui = {};
var 탭 = 함수 (elem, opts) {
this.elem = elem;
this.opts = opts;
};
var tabproto = tab.prototype;
/ * 업데이트 시간 2015 1/26 15:36 */
tabproto._isdisplaymax = function (size) {
var displaymax = this.getOpts () [ "displayMax"] || 5;
return (size <= displaymax)? 사실 : 거짓;
};
tabproto._isemptyresult = function () {
if (! this.getOpts () [ "result"]. length) {
거짓을 반환합니다.
}
진실을 반환하십시오.
};
tabproto._saveorupdatestatus = 함수 (항목, 상태) {
항목 [ "상태"] = 상태;
};
tabproto._getItemListByStatus = function (status) {
var list = [];
var result = this.getOpts () [ "결과"];
$ .Each (result, function (i, item) {
if (status == item [ "status"]) {
list.push (항목);
}
});
반환 목록;
};
tabproto._getStatusByIndex = function (index) {
var status = null;
var result = this.getOpts () [ "결과"];
$ .Each (result, function (i, item) {
if (index == item [ "index"]) {
상태 = 항목 [ "상태"];
}
});
반환 상태;
};
tabproto._renderconsolepanel = function (status) {
var that = this;
var root = that.getElem (). find ( ". console-panel");
this._resetconsolepanel ();
$ .Each (that._getItemListByStatus (상태), 함수 (i, item) {
var elem = $ ( "<div style = 'float : 왼쪽';> </div>"). Appendto (root);
$ ( "<input type = 'radio'name = 'addMod' />")
.Data ( "항목", 항목)
.appendto (elem);
$ ( "<span> </span>"). 텍스트 (항목 [ "text"]). 부록 (elem);
});
if (root.find ( "div"). size ()) {
$ ( "<input type = 'button'value = 'module add module'style = 'margin-left : 20px'/>")
.on ( "클릭", function () {
var data = root.find ( "입력 [type = radio] : checked"). data ( "item");
if (that._getItemListByStatus ( "1"). length <that.getOpts () [ "displayMax") {
that.getelem (). find ( ". title .items div"). eq (data [ "index"]). fadein (function () {
that._saveorupdatestatus (data, "1");
})
.Trigger ( "클릭");
}
또 다른{
that._saveorupdatestatus (data, "2");
}
that.getElem (). find ( ". title .adder"). trigger ( "click");
})
.appendto (루트);
}
또 다른{
root.text ( "아직 추가 할 항목 없음!");
}
};
/ * 업데이트 시간 2015 1/26 15:36 */
tabproto._setCurrent = function (index) {
var items = this.getElem (). find ( ". title .items div"). removeClass ( "active");
items.eq (index) .addclass ( "active");
var contents = this.getElem (). find ( ". content .c"). hide ();
contents.eq (index) .show ();
};
tabproto.getelem = function () {
이 this.elem;
};
tabproto.getopts = function () {
this.opts를 반환합니다.
};
tabproto._resetContent = function () {
this.getElem (). find ( ". content"). html ( "");
};
tabproto._setContent = function (html) {
this.getElem (). find ( ". content"). html (html);
};
tabproto._getContent = function (url) {
return $ .ajax ({
URL : URL
});
};
tabproto._deleteitem = function (elem) {
var that = this;
this.getElem (). find ( ". title .items div")
.eq (elem.index ())
.fadeout (function () {
that._resetContent ();
that._saveorupdatestatus (elem.data ( "항목"), "0");
that._triggeritem (elem.index () + 1);
});
};
tabproto._triggeritem = function (다음) {
var nextstatus = this._getStatusByIndex (다음);
var 항목 = this.getElem (). find ( ". title .items div");
다음 = 항목 .eq (다음);
if (next.size () && "1"== Nextstatus) {// 후속 DOM 노드가 존재합니다.
다음. 트리거 ( "클릭");
}
또 다른{
items.eq (0) .trigger ( "클릭");
}
};
tabproto._ResetConsoLepanel = function () {
this.getElem (). find ( ". console-panel"). empty ();
};
tabproto.init = function () {
if (this._isemptyresult ()) {
this._setContent ( "아직 모듈 없음!");
}
var that = this;
this.getElem (). find ( ". title .adder")
.Text ( " +" + this.getOpts () [ "ButtonText"]))
.on ( "클릭", function () {
that.getelem (). find ( ". console-panel"). slidetoggle (function () {
that._renderconsolepanel ( "0");
});
});
$ .Each (this.getOpts () [ "result"], function (i, item) {
if (that._isdisplaymax (i + 1)) {
that._saveorupdatestatus (항목, "1");
}
또 다른{
that._saveorupdatestatus (항목, "2");
}
that._render (항목);
});
if (! that._isdisplaymax (this.getOpts () [ "result"]. length)) {
this.getElem (). find ( ". title .more-mod"). fadein (function () {
$ (this) .find ( ". tag"). on ( "click", function () {
var root = $ (this) .next ();
root.empty ();
$ .Each (that._getItemListByStatus ( "2"), 함수 (i, data) {
$ ( "<div> </div>"). Text (data [ "text"])
.on ( "클릭", function () {
if (that._getItemListByStatus ( "1"). length <that.getOpts () [ "displayMax") {
that.getelem (). find ( ". title .items div"). eq (data [ "index"]). fadein (function () {
that._saveorupdatestatus (data, "1");
});
}
또 다른{
ALERT ( "모듈이 추가 될 수 없으며 현재 최대 숫자입니다!");
}
})
.appendto (루트);
});
root.toggle ();
});
});
}
this.getElem (). find ( ". title .items div")
.eq (0)
.Trigger ( "클릭"); // 하나가 있어야한다고 가정합니다. 그렇지 않으면 플러그인이 의미가 없습니다!
};
tabproto._render = function (data) {
var that = this;
var item = $ ( "<div> </div>"). text (data [ "text"]). AppendTo (this.getElem (). find ( ". title .items"));
데이터 [ "index"] = item.index ();
item.on ( "클릭", function () {
that._setCurrent ($ (this) .index ());
that._getContent (data [ "url"]). done (function (result) {
that._setContent (결과);
})
.fail (function () {
새 오류를 던지십시오 ( "순 오류!");
});
})
.Data ( "항목", 데이터);
if ( "2"== data [ "status"]) {
item.hide ();
}
if ( "1"== data [ "showClose"]) {
$ ( "<span class = 'del'> x </span>")
.on ( "클릭", function () {
if (win.confirm ( "이 항목이 삭제됩니까?")) {
that._deleteitem (항목);
거짓을 반환합니다. // 거품을 멈 춥니 다
}
})
.appendto (항목);
}
};
ui.createtab = function (elem, opts) {
var 탭 = 새 탭 (Elem, Opts);
tab.init ();
리턴 탭;
};
}) (jQuery);
(iv), 최종 요약
(1) 객체 지향적 사고 방식에서 기능적 요구 사항에 대한 합리적인 분석.
(2), 플러그인 로직을 수업 방식으로 구성하십시오.
(3) 위의 예를 지속적으로 재구성하는데,이를 합리적으로 재구성하는 방법은 무엇입니까? 과도하게 설계하지 마십시오. 권장 방법은 프로세스 설계와 객체 지향적 사고 설계를 결합하는 것입니다.