4
什麼是谷歌關閉的解決方案,用於解決在JavaScript回調函數中關鍵字this
的問題。它在OO風格編程中非常有用。谷歌關閉綁定/解決這個關鍵字問題
是否有谷歌關閉任何約定或樣式OOP ???
更新 我怎樣才能訪問this.darklayer在ViewportSizeMonitor處理???
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.math.Size');
goog.require('goog.style');
goog.require('goog.dom.ViewportSizeMonitor');
goog.provide('ehsun7b.ajax.AjaxBox');
ehsun7b.ajax.AjaxBox = function (url, containerClass) {
try {
this.url = url;
this.containerClass = containerClass;
var viwportSize = goog.dom.getViewportSize();
this.darklayer = goog.dom.createDom("div", {
"style": "width: " + viwportSize.width + "px;" + "height: " +
viwportSize.height + "px;" +
"background-image: url('css/img/50black.png');" +
"z-index: 1000;" +
"position: absolute;" +
"left: 0px; top: 0px;"
});
var vsm = new goog.dom.ViewportSizeMonitor();
goog.events.listen(vsm, goog.events.EventType.RESIZE, function(e) {
console.log("this: " + this.darklayer);
});
this.container = goog.dom.createDom("div", {
"class": this.containerClass
});
goog.dom.appendChild(this.darklayer, this.container);
goog.dom.setTextContent(this.container, "hello ajax box");
this.show = function() {
goog.dom.appendChild(document.body, this.darklayer);
},
this.hide = function() {
goog.dom.removeNode(this.darklayer);
}
} catch (e) {
console.log("error: " + e);
}
};
我根據Closure的風格這種方式改變了我的類:
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');
goog.require('goog.math.Size');
goog.require('goog.style');
goog.require('goog.dom.ViewportSizeMonitor');
goog.provide('ehsun7b.ajax.AjaxBox');
ehsun7b.ajax.AjaxBox = function (url, containerClass) {
try {
this.url = url;
this.containerClass = containerClass;
var viwportSize = goog.dom.getViewportSize();
this.darklayer = goog.dom.createDom("div", {
"style": "width: " + viwportSize.width + "px;" + "height: " +
viwportSize.height + "px;" +
"background-image: url('css/img/50black.png');" +
"z-index: 1000;" +
"position: absolute;" +
"left: 0px; top: 0px;"
});
var vsm = new goog.dom.ViewportSizeMonitor();
goog.events.listen(vsm, goog.events.EventType.RESIZE, function(e) {
console.log("this: " + this.darklayer);
});
this.container = goog.dom.createDom("div", {
"class": this.containerClass
});
goog.dom.appendChild(this.darklayer, this.container);
goog.dom.setTextContent(this.container, "hello ajax box");
} catch (e) {
console.log("error: " + e);
}
};
ehsun7b.ajax.AjaxBox.prototype.show = function() {
goog.dom.appendChild(document.body, this.darklayer);
}
ehsun7b.ajax.AjaxBox.prototype.hide = function() {
goog.dom.removeNode(this.darklayer);
}
很不錯的,我不那麼熟悉的風格和'谷歌Closure'約定,我可以問你看到我的課'AjaxBox'在我的問題更新,並告訴我我如何在ViewportSizeMonitor'handler'中訪問'this.darklayer'? – ehsun7b
我找到了解決方案謝謝(使用處理程序)。 – ehsun7b
另外,不要將goog.require()語句放在與使用goog.required函數或類的代碼的入口點相同的腳本標記中。 goog.require()調用在包含調用的腳本標籤之後向文檔添加代碼。更多:https://developers.google.com/closure/library/docs/gettingstarted – djreed