2013-04-17 34 views
0

我開始學習backbone.js並開發一個示例骨幹應用程序,其中來自高音揚聲器API的主幹視圖中填充了搜索項的推文源。爲什麼backbone.js在本例中不呈現視圖?

以下是我的骨幹MVC代碼。

BackboneSample.js

$(function() { 
    var Tweet = Backbone.Model.extend(); 

    var Tweets = Backbone.Collection.extend({ 
     model: Tweet, 
     url: 'http://search.twitter.com/search.json?q=NYC&callback=?', 
     parse: function(response) { 
      console.log('parsing ...'); 
      console.log('parsing ...'); 
      return response.results; 
     } 
    }); 
    var PageView = Backbone.View.extend({ 
     el: $('body'), 
     events: { 
      'click button#add': 'doSearch' 
     }, 
     initialize: function() { 
      _.bindAll(this); 
      this.tweets = new Tweets(); 
      _this = this; 
      this.tweets.on('reset', function(collection) { 
       _this.$('#tweets').empty(); 
       collection.each(function(tweet) { 
        _this.addItem(tweet); 
       }); 
      }); 
      this.counter = 0; 
      this.render(); 
     }, 
     doSearch: function() { 
      var subject = $('#search').val() || 'NYC'; 
      this.tweets.url = 'http://search.twitter.com/search.json?q=' + subject + '&callback=?'; 
      this.tweets.fetch(); 
     }, 
     render: function() { 
      $(this.el).append("<input id= 'search'type='text' placeholder='Write a word' />"); 
      $(this.el).append("<button id='add'>Search twitts</button>"); 
      $(this.el).append("<ul id='tweets'></ul>"); 
      return this; 
     }, 
     addItem: function(item) { 
      console.log(item); 
      $('ul', this.el).append("<li><b>" + item.get('from_user_name') + "</b>: " + item.get('text') + "</li>"); 

     } 
    }); 
    var pageView = new PageView(); 
}); 

但這種如我所料不工作。呈現頁面後,推文不會進入視圖。 JSON響應數據從高音揚聲器API返回,但該視圖並未反映該變化。這裏會發生什麼錯誤?我如何解決這個問題?

請檢查demo小提琴。

+1

PS:'_this = this;'創建一個全局變量,你想'var _this = this;'。當你已經擁有['this。$ el'](http://backbonejs.org/#View-$el);不要打擾$(this.el)';同樣,當你有['this。$'](http://backbonejs.org/#View-dollar),'this。$('ul' )'會更習慣。 –

+0

@ muistooshort謝謝,我已根據您的建議進行了更改,並且工作完美無瑕。 –

回答

2

由於骨幹fetch的1.0版本不會自動觸發重置事件,而會使用collection.set來將提取的模型與您已有的其他模型合併。爲了有效地重置您的收藏,你應該改變你取這樣調用:

官方 docs
this.tweets.fetch({reset:true}); 

更多信息。

+0

偉大的職位,作品像一個魅力。我們如何在提取參數中使用'collection.set'而不是'reset:true'? –

+0

我認爲你應該綁定你的集合來監聽同步事件而不是重置,像這樣:'this.tweets.on('sync',function(collection){'。你可以檢查所有的內置事件[這裏](http://backbonejs.org/#Events)。 – Ingro

0

骨幹視圖有2個屬性。

  • el - 保存容器選擇器。
  • $ el - jQuery元素。

您正在初始化錯誤。你需要具體說明

el: 'body' or $el: $('body') 
相關問題