2013-07-11 77 views
0

我定義上require.js我的文件配置如下模式()doesn't工作:骨幹:引導加載頁面上require.js

require.config({ 
    shim: { 
     'underscore': { 
      exports: '_' 
     }, 
     'backbone': { 
      deps: ['underscore', 'jquery'], 
      exports: 'Backbone' 
     }, 
     'bootstrap': { 
      deps: ['jquery'] 
     } 
    }, 
    paths: { 
     jquery: 'libs/jquery-1.10.1', 
     underscore: 'libs/underscore', 
     backbone: 'libs/backbone', 
     bootstrap: 'libs/bootstrap', 
     templates: '../templates' 
    } 
}); 

require(['app'], function (App) { 
    App.initialize(); 
}) 

這是我的看法:

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

     var MainView = Backbone.View.extend({ 

      el: $('.container'), 

      events: { 
       'click .nav-link.login': 'loginModal' 
      }, 

      loginModal: function() { 
       this.$('#login-email, #login-password').val(''); 
       this.$('#login-modal .alert').addClass('hide'); 
       this.$('#login-modal').modal(); 
      } 

     }); 

     return MainView; 

}); 

當我點擊nav-link.login時,會觸發函數'loginModal',但它沒有顯示我的模態形式,其他指令工作。如果我打開javascript控制檯並寫這個。$('#login-modal')。modal(),它的工作原理。

我看在DOM和自舉如下加載:

<script type="text/javascript" charset="utf-8" async="" data-requirecontext="_" data-requiremodule="bootstrap" src="js/libs/bootstrap.js"></script> 

有人能幫助我嗎?

回答

1

它看起來像你的MainView的$ el是空的,你還沒有指定一個模板來使用它。所以,從本質上講,當你在loginModal中引用「this」時,它試圖找到與你的jquery選擇器相匹配的第一個DOM元素 - 但它正在尋找裏面的視圖$ el,它是空的。當您從控制檯嘗試它時,「this」將成爲全局文檔範圍,因此您可以找到它。

我的建議是將你的mainview的html加載到一個下劃線模板,並將其渲染到主幹的標準渲染函數中。或許,這將是這個樣子:

define([ 
    'jquery', 
    'underscore', 
    'backbone', 
    'bootstrap', 
    '!text/path_to_html_templates/MainView.html' 
], function ($, _, Backbone, Bootstrap, mainViewTemplate) { 

    var MainView = Backbone.View.extend({ 

     $el: $('.container'), 

     template: _.template(mainViewTemplate), 

     events: { 
      'click .nav-link.login': 'loginModal' 
     }, 

     loginModal: function() { 
      this.$('#login-email, #login-password').val(''); 
      this.$('#login-modal .alert').addClass('hide'); 
      this.$('#login-modal').modal(); 
     }, 

     render: function() { 
      this.$el.html(this.template()); 
     } 

    }); 

    return MainView; 

}); 

我不知道夠不夠你的UI結構,以幫助你遠不止這些,但希望至少給你一個起點。