2012-05-15 22 views
0

我已經定義了綁定到集合的視圖。取回集合時未調用渲染函數

1)當我初始化視圖時,執行集合上的獲取調用。 2)如果我看看獲取請求的結果,這是好的
3)我想觸發此變化(在myCollection中)調用渲染功能,但它不起作用。

這裏是我的代碼部分:

define([ 
    "MyCollection", 
    "!text/template" 
], function (myCollection, myTemplate) { 

    var myView = Backbone.View.extend({ 

     initialize: function() 
     { 
      myCollection.bind('change', this.render); // why the render is not called when 
                 // I perform the fetch even if the data is correctly loaded? 

      myCollection.fetch(); // it works 
     }, 

     render: function() 
     { 
      // some code 
      this.$el <-- undefined 
     } 

    }); 

    return myView; 
}); 

如果我使用

1)

initialize: function() 
    { 
     myCollection.bind('reset', this.render); // this.$el <-- undefined in render call, Why? 

     myCollection.fetch(); // it works 
    } 

2)

myCollection.fetch({ 
    success: function() { 
     that.render(); // <-- here the $el is defined and it works, Why myCollection.bind('reset', this.render); not?? 
     // it seems to me that when I use reset the render function is called before the this.$el is defined 
    } 
}); 

回答

1

您必須收聽reset事件,而不是change事件。

這樣:

myCollection.bind('reset', this.render, this); 
+0

成功完成change事件如果我在復位改變我得到以下信息:'遺漏的類型錯誤:無法調用未定義的方法'html'。在我的問題中更多詳細信息 – underscore666

1

骨幹觸發"reset" event,而不是一個fetch()

var myView = Backbone.View.extend({ 

    initialize: function() 
    { 
     myCollection.bind('reset', this.render); 
     myCollection.fetch(); // it works 
    }, 

    render: function() 
    { 
     // some code 
    } 

}); 
+0

如果我在重置中更改,則會收到以下消息:'未捕獲的TypeError:無法調用未定義的方法'html'。我的問題更多詳情 – underscore666

+0

你在哪裏設置你的el?在實例化? –