[英]javascript design pattern on page with 2 or more objects
我需要選擇正確的設計模式。 我的頁面有2個從同一個構造函數創建的對象。 我遇到的問題是檢測哪個對象正在獲取點擊事件。
我在創建對象后這樣做:
$("table tr, table button,.dataTables_paginate a").click(function (e) {
**myTableName.buttonPressed($(this));**
});
和
buttonPressed: function (el) {
if (el.is('a') && el.closest('li').hasClass('paginate_button')) {
var objName = el.attr('aria-controls');
debugger;
}
else {
var objName = $(el).closest('table').attr('id');
}
**this.getName(objName);**
tbl = myTableName.tbl;
editor = myTableName.editor;
//myTableName.acl(myTableName.currentForm);
},
接着
getName: function (objName) {
// search through the global object for a name that resolves to this object
for (var name in window)
if (window[name] == this) {
if (objName) {
myTableName = window[objName];
//window.myState[this.myInstanceName] = jQuery.extend({}, this);
break;
} else {
window[name] = this;
window[window[name]] = window[name];
myTableName = window[window[name]];
// window.myState[this.myInstanceName] = jQuery.extend({}, this);
}
break;
}
},
除了這些都是全局的,我不會這是正確的方法來做到這一點。
思考?
看來你應該使用自定義屬性。 自定義屬性允許您將其他相關數據存儲到任何DOM元素。 可以使用的一種方法是將DOM與一些JS字節碼相關聯。 當您必須向后工作時,即在查找HTML元素的相關對象時,這尤其有用。 標准說這些屬性必須從data-
開始 - (雖然從技術上講,你可以使用瀏覽器不使用的任何東西,但不建議這樣做)。 這是一個例子:
HTML:
<table data-instance-name="name1">
...
<button>Action</button>
<a>Another action</a>
</table>
<table data-instance-name="name2">
...
<button>Action</button>
<a>Another action</a>
</table>
JS:
$( 'table button, table a' ).on('click', function() {
var name = $(this).closest('table').attr('data-instance-name'),
table = tables[name];
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.