【问题标题】:Backbone get set throws error after clone model?克隆模型后,Backbone get set 抛出错误?
【发布时间】:2018-12-06 02:13:41
【问题描述】:

我有一个客户模型,它的细节很少,如下所示

customerModel.FIRST_NAME.get('value'); // this will give some name, works fine!

现在如果我像下面这样克隆模型

 var cloneModel = _.cloneDeep(customerModel);
 cloneModel.FIRST_NAME.get('value'); 
 // This gives  Uncaught TypeError: cloneModel.FIRST_NAME.get is not a function

请告知我在这里缺少什么?为什么克隆后主干获取/设置不起作用?

提前致谢

【问题讨论】:

  • 如果你想要一个新的主干模型,为什么要克隆而不是创建具有相同数据的新模型实例?

标签: javascript jquery backbone.js lodash


【解决方案1】:

在 lodash _.cloneDeep 之后,骨干获取/设置不再起作用,因为 _.cloneDeep 复制对象的属性(即模型的属性),但不是原型。见下例:

// Updating the prototype with new properties
var MyModel = Backbone.Model.extend({
  myProperty: 'foo',
  myFunc: _.noop
});
var myModel = new MyModel({value: 'someValue'});
var cloneModel = _.cloneDeep(myModel);
console.log(myModel.get);
// ƒ (e){return this.attributes[e]}
console.log(myModel.myProperty);
// 'foo'
console.log(myModel.attributes.value);
// 'someValue'
console.log(cloneModel.get);
// undefined
console.log(cloneModel.myProperty);
// undefined
console.log(cloneModel.attributes.value);
// 'someValue'

你想改用的是Backbone.Model's clone function

// Updating the prototype with new properties
var MyModel = Backbone.Model.extend({
  myProperty: 'foo',
  myFunc: _.noop
});
var myModel = new MyModel({value: 'someValue'});
var cloneModel = myModel.clone();
console.log(myModel.get);
// ƒ (e){return this.attributes[e]}
console.log(myModel.myProperty);
// 'foo'
console.log(myModel.attributes.value);
// 'someValue'
console.log(cloneModel.get);
// ƒ (e){return this.attributes[e]}
console.log(cloneModel.myProperty);
// 'foo'
console.log(cloneModel.attributes.value);
// 'someValue'

在任何情况下都应该这样做,因为即使 _.cloneDeep 按预期工作,您也会有两个具有相同 cid 的模型实例,这可能会导致事件发生问题。

【讨论】:

    猜你喜欢
    • 2013-05-30
    • 2023-03-14
    • 2013-07-05
    • 2022-01-11
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 2015-08-18
    • 1970-01-01
    相关资源
    最近更新 更多