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'
});

相关文章

事件冒泡和事件捕获 起因:今天在封装一个bind函数的时候,发现el.addEventListener函数支持第三个参数...
js小数运算会出现精度问题 js number类型 JS 数字类型只有number类型,number类型相当于其他强类型语言...
什么是跨域 跨域 : 广义的跨域包含一下内容 : 1.资源跳转(链接跳转,重定向跳转,表单提交) 2.资源...
@ &quot;TOC&quot; 常见对base64的认知(不完全正确) 首先对base64常见的认知,也是须知的必须有...
搞懂:MVVM模式和Vue中的MVVM模式 MVVM MVVM : 的缩写,说都能直接说出来 :模型, :视图, :视图模...
首先我们需要一个html代码的框架如下: 我们的目的是实现ul中的内容进行横向的一点一点滚动。ul中的内容...