2011-05-17 82 views
0

我正在使用backbone.js構建一個js沉重的應用程序,我遇到過幾次的一個問題是如何從深度嵌套調用外部對象功能,在下面的代碼示例中,我想打電話給custom_function事件時幻燈片事件發生。什麼是做到這一點的最好方法是什麼?從嵌套函數訪問外部對象(使用backbone.js

App.Views.Category = Backbone.View.extend({ 
    ...., 
    render: function() { 

     $('#slider').slider({ 
      min:0, 
      max:100, 
      slide: function(event, ui) { 
       //HOW DO I CALL THE custom_function from here???? 

      }, 

     }); 
    }, 

    custom_function: function() { 
     alert('in custom function'); 
    }, 


}); 

ASDF

回答

2

有兩種常用的選項。

您可以將this轉換爲thatself然後調用它。

render: function() { 
    var that = this; 
    $('#slider').slider({ 
     min:0, 
     max:100, 
     slide: function(event, ui) { 
      //HOW DO I CALL THE custom_function from here???? 
      that.custom_function(); 
     }, 

    }); 
}, 

或者你可以綁定函數的上下文。

render: function() { 
    $('#slider').slider({ 
     min:0, 
     max:100, 
     slide: (function(event, ui) { 
      //HOW DO I CALL THE custom_function from here???? 
      this.custom_function(); 
     }).bind(this), 

    }); 
}, 

Function.prototype.bind是ES5只所以用_.bind$.proxy跨瀏覽器支持

+0

我想你之前所擁有的第一種方法。 「this」總是會給我「#slider」dom元素,「that」將是空的。對於第二種方法,我從jquery中得到「handlers.push in not a fucntion」錯誤。 – DevX 2011-05-17 19:06:47

+0

@DevX'.bind'只能在chrome/FF3.6 +/IE9中運行,所以在這些地方試試吧。你的描述聽起來像是一個非常奇怪的錯誤。 – Raynos 2011-05-17 19:12:55

+0

不管怎樣,我可能會使用_.bind作爲跨瀏覽器支持。在這種情況下,_.bind的語法是什麼? – DevX 2011-05-17 19:15:24