2012-11-22 30 views
1

我有一個觀點在.js文件分開「的index.html」文件看起來像這樣:多文件Backbone.js的應用似乎並沒有工作

window.App = Backbone.View.extend({ 
     el: $('#article'), 

     initialize: function() { 
      _.bindAll(this, 'render'); 
      console.log('binding'); 
      console.log($('#article')); 
      this.render(); 
     }, 

     render: function() { 
      console.log('rendering'); 
      this.$el.html("rendered"); 
      return this; 
     } 
    }); 

我分配在該視圖'index.html'使用JQuery的ready函數:

<div id="article"> 
</div> 

<script type="text/javascript"> 
    $(function(){ 
     console.log($('#article')); 
     new window.App(); 
    }); 
</script> 

正如您所猜測的,「呈現」不會出現在DOM上。問題是,當我把所有東西放在一起時(視圖和標籤中的分配),它就可以工作。

任何想法?

+0

這是什麼'的console.log(window.App)'有,如果你把它說在'$(函數(){...})'? –

+0

'function(){a.apply(this,arguments)}' – Muenodi

回答

4

我覺得你的問題是這樣的:

window.App = Backbone.View.extend({ 
    el: $('#article'), 

這個HTML之前發生:

<div id="article"> 
</div> 

通過瀏覽器看到的。這將使$('#article')爲空,您的render方法將無法訪問DOM中的任何內容。打開控制檯,並運行這個演示,你會看到你所看到的:http://jsfiddle.net/ambiguous/7sGcZ/

最簡單的解決方法是使用選擇爲el

window.App = Backbone.View.extend({ 
    el: '#article', 

,讓骨幹把它變成一個DOM元素在其自己的。這樣,當Backbone需要創建視圖的$el時,$('#article')會發現一些東西。

演示(的作品):http://jsfiddle.net/ambiguous/Vd6jP/

+0

不知道!謝謝 ! – Muenodi