微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/js/158676.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐