我開始學習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小提琴。
PS:'_this = this;'創建一個全局變量,你想'var _this = this;'。當你已經擁有['this。$ el'](http://backbonejs.org/#View-$el);不要打擾$(this.el)';同樣,當你有['this。$'](http://backbonejs.org/#View-dollar),'this。$('ul' )'會更習慣。 –
@ muistooshort謝謝,我已根據您的建議進行了更改,並且工作完美無瑕。 –