解決!看到問題的結尾,我用的結果jQuery關不工作,因爲我預期
我想寫一個函數,可以處理我的應用程序按路徑分頁。
我有一個函數route()被調用,參數是要移動到的路徑(頁面)。
route是一個對象,它定義了一個處理其邏輯的模型。 此模型包含3個功能 indexAction - 這呈現我的看法,並將其附加到我的頁面。 bindEvents - 這是我已經把我所有的點擊事件 關機 的 - 這是指令轉移到一個新的頁面
路由功能首先運行關閉當前頁面上運行時,在這裏我有$ (選擇).off()和$(選擇)一個.remove()
它然後運行enidexAction和bindEvents功能。
我現在的問題是,當我回到這個頁面,我所有的點擊功能都運行兩次,然後三次等等......它好像斷()從來沒有真正從錨解除綁定。
這裏是我的模型
var NewPageModel = (function() {
var instance;
var modal = 'null';
function createInstance() {
var object = {
indexAction: indexAction,
shutDown: shutDown,
bindEvents: bindEvents
};
return object;
}
function indexAction (data, callback){
var partials = {};
ViewManager.render('pageName',{context:data}, partials,function(html){
ViewManager.appendUnique('#xxx',html,'uniqueID');
callback();
});
}
/**
* Remove modal
*/
function shutDown(){
this.modal.off();
this.modal.remove();
}
function bindEvents() {
if(this.modal!='null'){
return;
}
this.modal = $(PagerManager.pages.newGroup.id);
this.modal.on('click','div.close', function() {
shutDown();
});
this.modal.on('click', 'button.cancel', function() {
shutDown();
});
this.modal.on('click', 'button.submit', function() {
//code that submits form information
});
}
return {
getInstance: function() {
if (!this.instance) {
this.instance = createInstance();
}
return this.instance;
}
};
})();
編輯之一的例子! 所以我仍然在學習有關範圍的重要性,以及如何可以應用到的功能 這裏是工作的代碼 VAR NewPageModel =(函數(){ VAR實例; VAR模態; 功能的createInstance(){ VAR對象= { 的indexAction:的indexAction, shutdown:關閉, bindEvents:bindEvents }; 返回對象; }
function indexAction (data, callback){
var partials = {};
ViewManager.render('pageName',{context:data}, partials,function(html){
ViewManager.appendUnique('#xxx',html,'uniqueID');
callback();
});
}
/**
* Remove modal
*/
function shutDown(){
this.modal.off();
this.modal.remove();
this.modal = null;
}
function bindEvents() {
//This is confused logic, if I use off() in shutdown, I don't need to do this as I need to bind all the events again. hence in shutdown modal=null;
if(!this.modal){
return;
}
this.modal = $('#modal');
this.modal.on('click','div.close', function() {
shutDown().apply(this);
}).bind(this);;
this.modal.on('click', 'button.cancel', function() {
shutDown().apply(this);
}).bind(this);;
this.modal.on('click', 'button.submit', function() {
//here I only use the apply(this) if I use another internal function
//code that submits form information
}).bind(this);;
}
return {
getInstance: function() {
if (!this.instance) {
this.instance = createInstance();
}
return this.instance;
}
};
})();
'如果(!this.modal = '空'){'真的花花公子? – AlienWebguy 2014-10-29 17:05:36
@AlienWebguy請提供一個更好的評價這個建議。我不是一個JavaScript開發人員,我正在嘗試...... – Beyerz 2014-10-29 17:09:29
除了JavaScript之外,存在'null'是因爲編程的原因 – AlienWebguy 2014-10-29 17:11:42