【问题标题】:Unable to get a model in Backbone collection by CID无法通过 CID 在 Backbone 集合中获取模型
【发布时间】:2013-03-06 10:08:59
【问题描述】:

我在主干中有以下模式/集合/视图设置。

var Card = {};  

//card model
Card.Model = Backbone.Model.extend();


//collection
Card.Collection = Backbone.Collection.extend({
    url: '/api/cards',
    model: Card.Model
});

//column view
Card.MainView = Backbone.View.extend({
        className: 'column',
        append: function(model) {
            var view = Card.View.extend({ 
                model : model,
                attributes: { cid : model.cid } 
            });
            var v = new view();
            this.$el.append(v.el);          
        },
        initialize: function() {
            var self = this;
            _.bindAll(this, "sortable");
            this.collection.fetch({ 
                success: function() { 
                    self.render(); 
                } 
            });
        },
        render: function() {
            var self = this;
            for(var i = 0; i < this.columns.length; i++) {
                var col = this.columns[i];
                var column = Card.ColumnView.extend({
                    data: col,
                    cards: self.collection.where({ position : col.position })
                });
                var col = new column();
                this.$el.append(col.el);
            }               
            this.sortable();
        },
        sortable: function() {
            var self = this;
            $(this.el).find('.card-container').sortable({
                connectWith: '.card-container',
                receive: _.bind(function(event, ui) { 
                    var cid = $(ui.item).attr('cid');
                    var card = self.collection.get(cid);
                    //console.log(self.collection.last());
                    console.log('cid', self.collection.get(cid));
                    console.log('index 1', self.collection.at(1));
                    console.log('last', self.collection.last());
                    console.log('collection', self.collection);
                }, this)

            });
        }
}); 

当我尝试从 sortable 函数中的 MainView 集合中获取模型时,它不会按 CID 记录模型。我得到以下输出。

cid undefined CardMetaCollection.js:97
index 1 d {collection: d, attributes: Object, _escapedAttributes: Object, cid: "c2", changed: Object…} CardMetaCollection.js:98
last d {collection: d, attributes: Object, _escapedAttributes: Object, cid: "c249", changed: Object…} CardMetaCollection.js:99
collection d {length: 249, models: Array[249], _byId: Object, _byCid: Object, url: "/api/cards"…}

我已尝试登录 fetch 方法的 success 回调,但我仍然得到未定义的返回...每个模型都有自己的 cid。非常感谢任何帮助。

【问题讨论】:

  • 您是否确保cid 属性实际上已附加到有问题的DOM 元素?你能做一个jsFiddle吗?

标签: javascript backbone.js backbone.js-collections


【解决方案1】:

.get() 方法接受idcidid 可以直接传递给get,但cid 必须作为对象字面量 传递。实际上,您也可以在对象字面量中传递 id 并使您的代码保持一致。

var cid = ...;
var card = self.collection.get({ cid: cid });

var id = ...;
var card = self.collection.get({ id: id });

var id = ...;
var card = self.collection.get(id);

您可以查看backbone.js 中的.get() 实现。

更新:单独的cid 可以传递给Backbone 0.9.9 或更高版本中的.get() 方法(请参阅implementation in the current 1.3.3)。

var cid = ...;
var card = self.collection.get(cid);

在您的情况下,问题可能出在卡片元素上缺少属性“cid”,正如Ben 所写。您声明了一个.append() 方法,将此属性添加到新元素,但您在.render() 方法中调用new column() 而不是它。看来,column 视图没有添加该属性,因为您的日志记录找到它undefined

注意:例如,请考虑使用有效的自定义 HTML 属性名称,例如“data-cid”,而不仅仅是“cid”。

【讨论】:

  • 在当前版本的 Backbone (v1.3.3) 中,这是不正确的 -- cid 确实可以直接传递给 .get() 方法。
【解决方案2】:
  • 确保您传递给self.collection.get(cid)cid 是任何一个模型的ID,因为collection.get 需要模型ID 作为参数。为此,您可能还需要记录 cid 值。

【讨论】:

    【解决方案3】:

    当您将不同的模型推送到一个集合并且休息时使用 cid 不响应所有请求的唯一 ID,或者 REST 不返回 ID attr 或者我们想要创建没有休息的假模型并将其推送到集合

     var banned = app.request('rest:banList');
      var whiteIp = app.request("rest:inviteList");
       var whiteGroup = app.request("rest:groupList");
                $.when(banned, whiteIp, whiteGroup).done(function (bannedList,  whiteIpList, whiteGroupList) {
                    debugger
                    var arr = new Backbone.Collection();
                    arr.add(bannedList);
                    arr.add(whiteIpList);
                    arr.add(whiteGroupList);
    
                });
    
    define(["app"], function (app) {
        var API = {
            getWho: function (data) {
                var whois = new Backbone.Model();
                whois.url = '/admin/whois';
                whois.cid = 'ban';
                var defer = $.Deferred();
    
                whois.fetch({
                    type: 'GET',
                    data: data,
                    success: function(data){
                        debugger
                        defer.resolve(data);
                    },
                    error: function(data){
                        defer.reject(data);
                    }
                });
                return defer.promise();
            }
        };
    
        app.reqres.setHandler("rest:getWho", function (data) {
            return API.getWho(data);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-29
      • 1970-01-01
      • 2011-11-20
      • 1970-01-01
      • 1970-01-01
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多