首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >backbone.js集合是否在创建时添加空元素?

backbone.js集合是否在创建时添加空元素?
EN

Stack Overflow用户
提问于 2011-07-07 00:15:21
回答 3查看 7.6K关注 0票数 16

我假设这要么是我的代码中的一个bug,要么是backbone.js的一个未记录的(据我所能找到的)特性。当我创建我的集合和我的视图时,该集合中已经有一个模型不是我创建的,或者我假设我没有创建,因为没有定义id。下面是我的代码。

代码语言:javascript
复制
// ---------------------------------------------------------- Work Order
window.WO = Backbone.Model.extend({
    default: {
        wonum: null,
        part:  null,
        desc:  null,
        comment: null,
        order: null,
        section: null
    },
    url: "/rest/wo/"
});
window.WOView = Backbone.View.extend({
    tagName: "tr",
    className: "wo",
    events: {
        "keypress .woComment"      : "updateOnEnter"
    },
    initialize: function(options)
    {
         _.bindAll(this, 'render', 'close', 'updateOnEnter');
        this.render = _.bind(this.render, this);
        this.model.bind('change', this.render);
    },
    render: function()
    {
        $(this.el).html(this.woTemplate(this.model.toJSON()));
        this.input = this.$('.woComment');
        this.input.bind('blur', this.close);
        return this;
    },
    woTemplate: _.template($('#woTemplate').html()),
    close: function()
    {
        this.model.set({comment: this.input.val()});
        this.model.save({},{contentType: 'application/jason'});
    },
    updateOnEnter: function(e) {
        if (e.keyCode == 13) this.close();
    }
});
// ------------------------------------------------------------- Section 
window.SectionC = Backbone.Collection.extend({
    comparator: function(woObj)
    {
        return woObj.get('order');
    }
});
window.Section = Backbone.Model.extend({
    defaults: {
        id: null,
        name: null
    },
    events: {
        'update' : 'doOrder',
        'change' : 'doOrder'
    },
    url: "/rest/section",
    woc: null,
    initialize: function()
    {
        this.woc = new SectionC({model: window.WO});
    },
    add: function(woObj)
    {
        this.woc.add(woObj);
        this.doOrder();
    },
    doOrder: function()
    {
        console.log("Calling doOrder");
        var that = this;
        var sel = "#sec"+this.get('id')+" .wo";
        $(sel).each(function(i,elem)
        {
            var elemID = $(elem).attr('id');
            var woObj = that.woc.get(elemID);
            woObj.set({order: i});
        });
    },
});

window.SectionView = Backbone.View.extend({
    tagName: "table",
    className: "section",
    initialize: function()
    {
        _(this).bindAll('add','remove','change');
        this.render = _.bind(this.render, this);
        this.mySort = _.bind(this.mySort, this);
    },
    sectionTemplate: _.template($('#sectionTemplate').html()),
    render: function()
    {
        this._rendered = true;
        var that = this;
        $(this.el).empty();
        $(this.el).attr('id',"sec"+this.model.get('id'));
        var woData = null;
        _(this.models).each(function(woObj)
        {
            var wov = new WOView({
                model: woObj,
                id: woObj.get('wonum')});
            woData += wov.render().el;
        });
        $(this.el).html(this.sectionTemplate({woData: woData}));
        return this;
    },
    add: function(woObj)
    {
        woObj.set({section: this.model.id, id: woObj.get('wonum')});
        this.model.add(woObj);
        if(this._rendered)
        {
            var wov = new WOView({
                model: woObj,
                id: woObj.get('wonum')});
            $(this.el).append(wov.render().el);
        }
        //this.mySort();
    },
    change: function()
    {
        this.render();
    },
    mySort: function()
    {
        var that = this;
        var sel = "#sec"+this.model.get('id')+" .wo";
        $(sel).each(function(i,elem)
        {
            var elemID = $(elem).attr('id');
            var woObj = that.model.woc.get(elemID);
            woObj.set({order: i});
        });
    },
    saveSection: function()
    {
        var json = {};
        json.section = this.model.get('id');
        json.order = {};
        var sel = "#sec"+this.model.get('id')+" .wo";
        $(sel).each(function(i,elem)
        {
            json.order[i] = $(elem).attr('id');
        });
        console.log(json);
        _(this.model.woc.models).each(function(woObj)
        {
            if(woObj.get('id') != "" && woObj.get('id') != undefined)
                woObj.save();
        });
    }
});
// ---------------------------------------------------------------- Page
window.PageC = Backbone.Collection.extend({
    comparator: function(obj)
    {
        return obj.get('order');
    }
});

window.PageView = Backbone.View.extend({
    tagName: "div",
    className: "prodSchedPage",
    initialize: function()
    {
        _(this).bindAll('add');
        this.render = _.bind(this.render, this);
    },
    render: function()
    {
        var that = this;
        this._rendered = true;
        $(this.el).empty();
        // Loop through the sections and render them
        _(this.collection.models).each(function(secObj)
        {
            var v = new SectionView({model: secObj, id: secObj.get('id')});
            $(that.el).append(v.render().el);
        });
        return this;
    },
    add: function(sectionObj)
    {
        this.collection.add(sectionObj);
        if(this._rendered)
        {
            this.render();
        }
    },
    addSection: function(sectionObj){this.add(sectionObj);},
    addWO: function(secID,woObj)
    {
        var secObj = this.collection.get(secID);
        if(secID = undefined)
        {
            alert("Error: Section does not exist!");
            return;
        }
        secObj.add(woObj);
    }
});

window.PSPage = new window.PageC({});
window.PSPV   = new window.PageView({collection: window.PSPage});
$("body").append(window.PSPV.render().el);
//window.PSPV.add(new Section({id: 1, name: "Section 1"}));
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-07-07 00:56:57

实例化集合时,第一个参数是模型数组,第二个参数是选项。

代码语言:javascript
复制
window.PSPage = new window.PageC({});

当您传入{}时,构造函数通过reset方法将参数传递给add方法,add方法检查参数是否为数组,如果不是,则数组将{}作为单一模型添加。backbone 0.5.1中的add方法如下(0.3.3的功能相同):

代码语言:javascript
复制
add: function(models, options) {

  if (_.isArray(models)) {
    for (var i = 0, l = models.length; i < l; i++) {
      this._add(models[i], options);
    }
  } else {
    this._add(models, options);
  }
  return this;
},

如果你没有向构造函数传递任何参数,你应该从一个空集合开始。

代码语言:javascript
复制
window.PSPage = new window.PageC();
票数 33
EN

Stack Overflow用户

发布于 2012-09-19 01:23:18

我遇到了同样的问题,因为我需要将参数传递给我的集合构造函数。如果我查看我的集合实例,它告诉我有零个模型,但是如果我使用each()迭代,它会发现那个不是我创建的幻影模型。

基于被接受的答案,我返回并再次查看API here

我的代码现在看起来像这样,它似乎避免了这个问题:

代码语言:javascript
复制
var myCollection = new MyCollection(new Array(), {
    setting1: "foo",
    setting2: "bar"
});
票数 3
EN

Stack Overflow用户

发布于 2014-04-07 16:45:01

来自backbone文档,用于构造/初始化集合:

代码语言:javascript
复制
new Backbone.Collection([models], [options])

这意味着,当你想用一些选项创建新的空集合时,你真的应该调用构造函数,第一个参数是空数组,而不是你的options对象(我简化了一点@killthrush代码,这样你就不需要输入'new Array()‘,而是使用[] ):

代码语言:javascript
复制
var myCollection = new MyCollection([], {
  setting1: "foo",
  setting2: "bar"
});

现在,在您的集合定义中,您应该具有类似于能够访问options对象的内容:

代码语言:javascript
复制
var myCollection = Backbone.Collection.extend({
    // add model, url, etc here
    initialize: function (models, options) {
        // use options here, e.g.
       this.setting1 = options.setting1;
       this.setting2 = options.setting2;
    }
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6599650

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档