2014-02-13 32 views
0
var viewModel = function (utils) { 
     this.x="GNC"; 
     this.tbl = null; }; viewModel.prototype.saveCords=function(){ alerts(this.x); }; 

$(function(){ 

var objViewModel=new viewModel(); 

$('#btnSaveCords').on('click',objViewModel.saveCords); // this is suppose to alert "GNC", but it doesnt 

}); 

那麼,如何獲取saveCords中的對象上下文而不是按鈕上下文?如何在本例中獲取對象上下文?

回答

0

你應該把參數

var objViewModel=new viewModel(utils_param_here); //here defined in function utils 

全碼:

var viewModel = function (utils) { 
     this.x="GNC"; 
     this.tbl = null; }; viewModel.prototype.saveCords=function(){ alerts(this.x); }; 

$(function(){ 

var objViewModel=new viewModel(this); 

$('#btnSaveCords').on('click',objViewModel.saveCords); // this is suppose to alert "GNC", but it doesnt 

}); 
1

的問題是默認的事件處理方法將有上下文的處理程序有針對性的DOM元素,你需要將其更改爲您的自定義對象。

使用$.proxy()通過自定義執行上下文的事件處理方法(可以使用Function.bind()但在IE < 9不支持)

var viewModel = function (utils) { 
    this.x = "GNC"; 
    this.tbl = null; 
}; 
viewModel.prototype.saveCords = function() { 
    alert(this.x); 
}; 

$(function() { 

    var objViewModel = new viewModel(); 

    $('#btnSaveCords').on('click', $.proxy(objViewModel.saveCords, objViewModel)); // this is suppose to alert "GNC", but it doesnt 

}); 

演示:Fiddle

相關問題