2016-01-17 42 views
3

在wapp.js我在JavaScript中有下面的類方法事件:創建JavaScript類

function Wapp() { 
    this.page = function($page_name) { 
     this.onLoad = function($response) { 

     } 
    } 
    this.navigate = { 
     changePage: function(link) { 
      // Ajax request to load the page 
      $.post(link, {}, function(response) { 
       // Code to display the page 
      }); 
     } 
    } 
} 

在app.js腳本我有以下代碼:

var wapp = new Wapp(); 

和我想要做到這一點:

wapp.page('home').onLoad(function() { 
    // doSomething(); 
} 

// When I call the method 'changePage' 
wapp.navigate.changePage('home'); 

// at the end of the page load 'home' I want to call the function 'doSomething()' inside the 'onLoad' method 

我應該如何定義類中的方法,以確保在某個動作結束時(在第是在ajax調用結束時)運行app.js中'onLoad'方法中定義的代碼?

回答

2

構建它時,您可以爲類指定一個函數作爲變量。您可以在以後調用分配的功能在你的代碼(例如,在其他功能結束)

https://jsfiddle.net/L8c2s6xr/

function func (functionToCall) { 
    this.functionToCall = functionToCall; 

    this.doSomething = function() { 
    this.functionToCall(); 
    } 
} 

var f = new func (
    function() { 
    alert('this works'); 
    } 
); 

f.doSomething();