2013-03-26 71 views
0

我想學習Backbone,我有幾個視圖工作得很好。這裏是我的問題的看法代碼:

var FavoritesView = Backbone.View.extend({ 
     el: 'favs', 
     render: function() { 
      var timesheets = new TimeSheet(); 
      var $that = $(this); 
      timesheets.fetch({ 
       data: { favorite: true}, 
       success: function(model, response, options) { 
        var template = _.template($('#favs-view').html(), { timesheets: model.models}) 
        $('.favs').html(template).addClass('well'); 
       } 
      }); 
     } 
     }); 

你可以看到,我取的集合,放在一個模板響應,然後顯示它。我無法從我的'成功'回調中獲得$ el。 $ that.el和$ that。$ el(我不知道區別)都是未定義的。我必須最終使用Jquery獲取元素並按照您所看到的附加模板。這工作,但這是一個黑客,我不喜歡它。任何幫助都會很棒。

回答

0

我拿它favs是一個類或一個id。嘗試添加.如果它是一個類,或者#如果它是一個ID,就在favs之前,如el: '.favs',。這是jquery選擇器語法。

1

我認爲你在這行

var $that = $(this); 

EL做錯了,是的對象不$(本)屬性。 所以,你應該只是做

var that = this; 

然後this.el不會是不確定的。檢查this.el這之間的這種working example

差異$ EL

$(this.el)的基本上$ EL緩存jQuery對象。閱讀更多在Backbone View Documentation

+0

'$(this)'只是包裝'這個'對象 – thinklinux 2013-03-26 10:05:47

+1

@thinklinux檢查這個http://jsbin.com/akovun/2/edit – sachinjain024 2013-03-26 10:13:32

+0

哦,你是對的。我的錯!他需要將'favs'改爲'.favs' – thinklinux 2013-03-26 10:21:15