4
我創建了一個jquery小部件,並且所有工作都正常,直到我需要另一個實例。那時我注意到兩個實例共享相同的數據。該插件應該跟蹤在表格中檢查哪些行,所以我不必在每次需要使用它們時都計算它們。如果我在兩個表上檢查小部件,請單擊一個表上的一行 - 兩個表都將具有相同的數據。這兩個表都發生這種情況。我只創建了幾個jquery小部件,所以我不確定這是怎麼發生的,但我已經通過代碼並可以看到它發生。當創建多個實例時,jquery小部件共享數據
看起來好像我錯誤地使用了widget工廠。感謝您提前提供任何幫助!
這裏是小部件代碼。
$.widget('ui.selectAndFilter', {
_init: function() {
},
_create: function() {
var self = this;
self.options.$mainTable = $(self.element).addClass(this.options.cssWidgetClass);
self.options.$mainTable.find('tbody tr').bind('click', function (e) {
self._onClick(e, $(this), false);
//Need to determine what todo with last param - redrawTables
});
},
options: {
cssWidgetClass: 'select-and-filter',
cssSelectedClass: 'selected',
$mainTable: {},
childTables: [],
canMultiSelect: false,
clickFinishedCallbacks: [],
minCount: 1
},
destroy: function() {
$(this.element).removeClass(this.options.cssWidgetClass);
},
_checkedIds: [],
checkRow: function ($tr) {
if ($.isDigit($tr))
$tr = $(this.options.$mainTable.find('tbody tr:eq(' + $tr + ')'));
if ($tr.length) {
var id = $tr.addClass(this.options.cssSelectedClass).find(':checkbox').attr('checked', true).val();
this._addId(id);
}
return this;
},
_uncheckRow: function ($tr) {
if ($tr.length) {
var id = $tr.removeClass(this.options.cssSelectedClass).find(':checkbox').attr('checked', false).val();
return this._removeId(id);
}
},
uncheckAllRows: function() {
var self = this;
this.options.$mainTable.find('tr.' + this.options.cssSelectedClass).each(function() {
self._uncheckRow($(this));
});
return self;
},
_removeId: function (id) {
this._checkedIds.splice(this._checkedIds.indexOf(id), 1);
return this._checkedIds;
},
_addId: function (id) {
if (this._checkedIds.indexOf(id) == -1)
this._checkedIds.push(id);
return this._checkedIds;
},
_onClick: function (event, $tr, redrawTables) {
if ($tr.hasClass(this.options.cssSelectedClass) && this._checkedIds.length > this.options.minCount) {
this._uncheckRow($tr);
} else {
if (!this.options.canMultiSelect) {
this.uncheckAllRows();
}
this.checkRow($tr);
}
this.redrawTables();
this._trigger('click');
},
redrawTables: function() {
$.each(this.options.childTables, function() {
this.fnDraw();
});
},
checkedIds: function() {
return this._checkedIds;
}
});
然後代碼來實例化它們。
tables['schedule'].selectAndFilter({canMultiSelect:selectMulti, childTables: redrawTables});
tables['start'].selectAndFilter({canMultiSelect: selectMulti})
tables['batch'].selectAndFilter({minCount:0});
固定 - 的_checkedIds是全球性的小部件,而不是個人的範圍之內上下文。 在_create函數中添加聲明。 this._checkedIds = []; – Brandon