2012-03-20 27 views
0

我一直無法使用jquery.AOP調用Backbone函數。它在全局函數和JavaScript模塊上運行良好。使用jquery.aop調用Backbone.js函數的範圍問題

require(['app', 'jquery' ], 
    function(App, $) {  
    App.initialize(); 
    $.aop.before({target: App.appRouter 
       method: 'helloWorld'}, 
      function() { 
       alert("before Hello World"); 
       } 
});  

在我的例子中,app.appRouter絕對是一個活着的實例變量。 這裏是應用程序與它的appRouter:

define([ 
'jquery', 
'underscore', 
'backbone' 
], function($, 
     _, 
    Backbone 
    ){ 

var appRouter = Backbone.Router.extend({ 
    initialize: function() { 
     //some code 
    }, 
    helloWorld: function(){ 
       alert("hello world"); 
     } 

}); 


var initialize = function(){ 
    this.appRouter = new appRouter(this); 
    Backbone.history.start(); 

}; 


return { 
     initialize: initialize, 
     appRouter : this.appRouter 

}; });

看起來像範圍問題,因爲以前的建議永遠不會達到。 感謝您的任何想法, 吉米

回答

0

這可能是一個時機問題。

$ .aop通過用新函數替換目標函數並維護對原始目標的引用來工作。當你調用這個函數時,它的aop版本被執行,並且它又調用原始函數。

鑑於此,嘗試用$.aop...呼叫交換的呼叫App.initialize()


$.aop.before({ 
    target: App.appRouter 
    method: 'helloWorld'}, 
    function() { 
    alert("before Hello World"); 

}); 
App.initialize(); 

我的另一個想法是,我沒有看到你的代碼正在調用該路由器的helloWorld方法的任何地方。你確定你真的在打電話嗎?

+0

我試過將兩個調用都交換到無效。是的,當單擊鏈接導致Backbone路由器的路由並將觸發器選項設置爲true時,該功能將被調用。這可能是jquery.aop無法調用它的原因。但是,調試時,Firebug中很好地存在App.appRouter.helloWorld函數。 – 2012-03-20 12:38:06

+0

最後一個想法,那麼:你的路由器是否有正確定義的路由?你不會在你發佈的代碼中顯示實際的'routes:{...}'。如果沒有定義路由,路由器將不會執行任何操作。 ...對不起,如果這是顯而易見的,只是關閉我在帖子中看到的 – 2012-03-20 12:44:59

+0

骨幹路由器正確地寫入路由,事件......但是我發現了一些東西:通過做$ .aop.before({target:App。 appRouter方法:''},function(){alert(「Hello World」之前);}); ,appRouter的所有功能都被正確地稱爲aop.before塊,是否有動態地獲取目標和方法?這可能最終導致我的調用者 – 2012-03-20 12:53:04