2011-12-02 88 views
2

我正在嘗試用Backbone做一個非常簡單的hello world。閱讀文檔和例子之後,我覺得這應該工作,但是當我點擊不會做任何事情:骨幹查看點擊世界你好

<!DOCTYPE html> 
<html> 
    <head> 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script> 
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script> 
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script> 
    <script type="text/javascript"> 
     var AppView = Backbone.View.extend({ 

      events: { 
       'click #new': 'createNew' 
      }, 

      //CREATE 
      createNew: function(){ 
       alert('yea'); 
      } 

     }); 

     var app_view = new AppView(); 
    </script> 
    </head> 
    <body> 

    <a href="#new" id="new">new</a> 
    </body> 
</html> 

我這麼想嗎?什麼可能是錯的?

回答

6

您這裏有兩個問題:

  1. 一個骨幹視圖綁定到特定的DOM元素。在響應事件之前,您必須將您的視圖附加到DOM。
  2. 當您的腳本執行時DOM可能沒有準備好,您必須用$(document).ready包裝視圖創建代碼。
<!DOCTYPE html> 
<html> 
    <head> 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script> 
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script> 
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script> 
    <script type="text/javascript"> 
     var AppView = Backbone.View.extend({ 

      events: { 
       // the element IS the link, you don't have to specify its id there 
       'click': 'createNew' 
      }, 

      //CREATE 
      createNew: function(){ 
       alert('yea'); 
      } 

     }); 

     $(document).ready(function() { 
     // attach the view to the existing a element 
     var app_view = new AppView({ 
      el: '#new' 
     }); 
     }); 
    </script> 
    </head> 
    <body> 

    <a href="#new" id="new">new</a> 
    </body> 
</html> 
+0

就是這樣,謝謝你benoit! – anders