2011-10-13 42 views
3

一個jQuery插件是這樣的:如何在其內部調用jQuery插件的方法?

var methods = { 
    init: function(options) { 
     $("#something").click(function() { 
      //call method show 
     }); 
    }, 
    show: function() { 
     //show something around here. 
    } 
} 

..

我如何調用該方法show裏面的方法init

回答

1

你可以使用proxy(),這就好比bind()只是它並不需要在那裏它不支持墊片...

$("#something").click($.proxy(function() { 
     // `this` is the same as `this` outside the function now. 
     this.show(); 
    }, this)); 
0

你可以使用一個關閉和捕捉當前對象的上下文(這個):

init: function(options) { 
    var _this = this; 
    $('#something').click(function() { 
     _this.show(); 
    }); 
} 

或者你也可以使用.bind()方法a第二參數傳遞給回調\

init: function(options) { 
    $('#something').bind('click', { _this: this }, function(evt) { 
     evt.data._this.show(); 
    }); 
} 

或直接與.click()方法:

init: function(options) { 
    $('#something').click({ _this: this }, function(evt) { 
     evt.data._this.show(); 
    }); 
} 
0

首先,你的代碼表明,要呼叫show#something單擊事件的內部。

其次,當你在初始化的背景下正在執行的,除非你說methods.init.call(...)以代替...一些其他的對象,然後thismethods。很可能,您將使用語句methods.init()。如果您只是將對象methods作爲插件傳遞給某個jQuery小部件,則這是正確的假設。以下將在這種情況下工作:

var methods = { 
     init: function(options) { 
      this.show(); 
     }, 
     show: function() {} 
    } 

除非你想使用點擊事件。在這種情況下,使用方法:

var methods = { 
     init: function(options) { 
      $('#something').click(function() { 
       this.show(); 
      }, this); // propogate this into click handler 
     }, 
     show: function() {} 
    } 

如果您希望您將運行methods.init.call(...),那麼你將需要確保建立一個封閉的範圍預先保持原有methods對象的軌跡:

var methods = function() { 
     // setup closure scope 
     var that = {}; // keep track of methods object 
     that.init = function() { 
      that.show(); 
     }; 
     that.show = function() { 

     }; 

     // return object with closure scope... will become `methods` 
     return that; 
    }(); 
相關問題