javascript – 使用带有主干的fetch更新集合

根据官方文档,当我做这样的事情时:
collection.fetch({update: true,remove: false})

我为每个新模型获得“添加”事件,并为每个更改的现有模型获得“更改”事件,而不删除任何内容.

为什么如果我调用静态数据源(集合的url总是返回相同的json),为每个收到的项调用add事件?

这里有一些代码(我没有渲染任何东西,我只是在调试):

<!doctype html>
<html>
  <head>
    <title>Example</title>
  </head>
  <body>
    <a href="#refresh">Refresh</a>
    <script src="js/jquery-1.8.3.min.js"></script>
    <script src="js/underscore-min.js"></script>
    <script src="js/backbone-min.js"></script>
    <script src="js/main.js"></script>
  </body>
</html>

继承人JS

(function($){
    //Twitter Model
    ModelsTwitt = Backbone.Model.extend({});
    //Twitter Collection
    CollectionsTwitts = Backbone.Collection.extend({
        model:ModelsTwitt,initialize:function(){
            console.log('Twitter App Started');
        },url:'data/195.json'
    });
    //Twitts View
    ViewsTwitts = Backbone.View.extend({
        el:$('#twitter-list'),initialize:function(){
            _.bindAll(this,'render');
            this.collection.bind('reset',this.render);
            this.collection.bind('add',this.add);
        },render:function(){
            console.log("This is the collection",this.collection);
        },add:function(model){
            console.log("add event called",model);  
        }
    });
    //Twitter Router
    Router = Backbone.Router.extend({
        routes:{
            '':'defaultRoute',//Default list twitts route
            'refresh':'refreshView'
        },defaultRoute:function(){
            this.twitts = new CollectionsTwitts();
            new ViewsTwitts({collection:this.twitts});
            this.twitts.fetch();
        },refreshView:function(){
            this.twitts.fetch({update:true,remove:false});
        }
    });
    var appRouter = new Router();
    Backbone.history.start();
})(jQuery);

基本上,我使用defaultroute获取集合,它使用所有模型和属性正确获取.

当我点击刷新链接时,我调用了refreshView,它基本上尝试用新模型更新集合.
我不明白为什么如果响应相同,集合的所有模型都被检测为新的,触发添加

Heres a functional link:打开控制台,即使集合相同,您也会看到在单击刷新时如何调用添加事件.

谢谢你的帮助.

解决方法

我的猜测是你的模型没有idAttribute (doc). Backbone查找的认键是id,你的JSON条目没有,所以它无法分辨哪些模型已经存在.

尝试将您的模型更改为此(或另一个键,如果这个不是唯一的):

ModelsTwitt = Backbone.Model.extend({
  idAttribute: 'id_event'
});

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...