다음과 같은 Dojo 위젯이 있습니다.
define([
// stuff...
], function(declare, lang, win, on, query,
_WidgetBase, _TemplatedMixin, _OnDijitClickMixin, template){
return declare("Toolbar", [_WidgetBase, _TemplatedMixin, _OnDijitClickMixin], {
templateString: template,
map: null,
constructor: function(options) {
// this.map set here
lang.mixin(this, options);
if (this.map === null) {
console.log("Error: no map!");
}
},
postCreate: function() {
on(this.domNode, ".toolButton:click", this.loadTool);
},
// in the following function, this refers to element where event
// originated here
loadTool: function(e) {
var clickedTool = "tools/Tool" + this.id[this.id.length - 1];
require([clickedTool], function(Tool) {
// Fails: want this.map to refer to map defined by constructor above
(new Tool({ map: this.map })).placeAt(win.body());
});
}
});
});
현재이 Toolbar
위젯은 정렬 된 버튼 목록 일 뿐이며 각 버튼에는 toolButton
. 버튼을 클릭하면 클릭 한 버튼과 관련된 모듈 (다른 위젯을 반환)을 조건부로로드합니다. 단순화를 위해 도구 모듈은 클릭 한 버튼 에서 가져온 tools/Tool<some_number>
위치 에 이름이 지정 됩니다.<some_number>
id
이 줄에서 볼 수 있듯이 위젯 의 map
속성을 Toolbar
위젯의 생성자에 전달해야합니다 Tool
.
(new Tool({ map: this.map })).placeAt(win.body());
내에, 전술 한 바와 같이, 그러나 loadTool
, this
받는 클릭하지 된 버튼을 의미 Toolbar
위젯. 한 가지 가능성은 이벤트 리스너를 다음과 같이 호출하는 것입니다.
on(this.domNode, ".toolButton:clicked", lang.hitch(this, this.loadTool);
그런 다음 id
이벤트 객체에서 클릭 한 버튼을 가져옵니다 ...하지만 이것은 엉뚱한 것처럼 보이고 잘못된 처리 방법과 같습니다.
이를위한 "모범 사례"는 무엇입니까?
가장 좋은 방법은 두 번째 접근 방식과 같이 컨텍스트를 콜백 함수에 전달하는 것입니다. 이를 통해 특히 비동기 작업에서 함수 실행 방법을 제어 할 수 있습니다.
dojo 문서에서 :
on(something, "click", processEvent);
위와 같은 비동기 콜백에서 코드가 실행되는 컨텍스트가 변경되었습니다. 더 이상 원래 제공 한 객체를 참조하지 않지만 컨텍스트는 이제 둘러싸는 객체 인 콜백을 참조합니다. 이 문제를 해결하려면 hitch ()를 사용하여 함수가 원래 컨텍스트를 유지하도록 할 수 있습니다.
올바르게 수행 된 동일한 코드는 다음과 같습니다.
on(something, "click", lang.hitch(this, processEvent));
http://dojotoolkit.org/reference-guide/1.10/dojo/_base/lang.html#dojo-base-lang-hitch
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다