为什么在这个例子中backbone.js没有渲染视图?

Why backbone.js doesn't render the view in this example?

本文关键字:视图 js backbone 为什么      更新时间:2023-09-26

我开始学习backbone.js并工作一个示例骨干应用程序,其中搜索词的tweet提要是根据tweeter API的骨干填充的。

下面是我的主干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响应数据从tweeter API返回,但视图没有反映更改。这里会发生什么错误?我怎样才能解决这个问题?

由于1.0版本的Backbone fetch不会自动触发重置事件,而是使用collection.set将获取的模型与您已经拥有的其他模型合并。为了有效地重置你的集合,你应该像这样改变你的fetch调用:

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

更多信息见官方文档

主干视图有2个属性。

  • el -保存容器选择器。
  • $el - jQuery元素。

初始化错误。你需要指定

el: 'body' or $el: $('body')