【问题标题】:backbone js getByCid not working骨干js getByCid不工作
【发布时间】:2018-08-04 17:17:31
【问题描述】:

当我在 console.log 中查看时,主干 getByCid 不起作用,它显示错误为 TypeError:test.getByCid 不是函数。通过使用 at(0).cid,它将输出显示为 'c1' 为什么它不工作。

var test=new Backbone.Collection([ 
   {name:'gowtham',age:10}
]);
console.log(test.at(0).cid); // output as c1
console.log(JSON.stringify(test.getByCid('c1'))); //TypeError: test.getByCid is not a function

【问题讨论】:

    标签: backbone.js backbone.js-collections


    【解决方案1】:

    Backbone.Collection 没有方法getByCid,这就是您收到此错误的原因。
    但是一个集合有get获取模型的方法。
    它接受一个参数:model | id | cid

    所以如果你想通过cid获取模型,你可以这样做collection.get(cidValue)

    let collection = new Backbone.Collection();
    let test1 = new Backbone.Model({ id: 1, value: 'first' });
    let test2 = new Backbone.Model({ id: 2, value: 'second' });
    
    collection.add([test1, test2]);
    
    console.log(collection.get(2));
    // find test2 by id
    
    console.log(collection.get('c2'));
    // find test2 by cid
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone.js"></script>

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 2013-10-14
      相关资源
      最近更新 更多