【问题标题】:KnockoutJS - Is there any easy way to overwrite observables with a single object?KnockoutJS - 有没有简单的方法可以用单个对象覆盖 observables?
【发布时间】:2012-07-01 04:24:02
【问题描述】:

考虑以下代码:

 // data comes from AJAX call response (entity from db)
 var template = ko.mapping.fromJS(data);

 if ( isAddMode ) {                            
     self.selectedCategory().EmailTemplates.push(template);
     self.selectedTemplate(template);
 } else {
     // why can't this work?!?
     //vmTemplates.selectedTemplate(template);                   

     // have to do this instead...
     self.selectedTemplate().Name(template.Name());
     self.selectedTemplate().Subject(template.Subject());
     self.selectedTemplate().Content(template.Content());
}

我有一个编辑电子邮件模板的对话框。保存模板后,使用映射插件从 AJAX 调用的响应创建“模板”对象。

如果我正在创建一个新模板 (isAddMode),那么我可以将模板推送到数组中,然后设置 selectedTemplate()。这会导致在添加模板的对话框关闭后,编辑器字段会在主 UI 上显示所有最新字段。

但是,如果我要更新模板(在 UI 上是同一个编辑器),我现在想将 selectedTemplate() 设置为映射的模板对象。但是,这没有效果。我能做到这一点的唯一方法是如上所述设置每个单独的属性。为什么我不能像推送一个新的 observable 那样一次性做到这一点?我觉得这与新的 observables 以某种方式与旧的 observables 分离这一事实有关。

【问题讨论】:

  • 你能在小提琴中重现这种行为吗?到目前为止似乎对我有用:jsfiddle.net/sU22b
  • 为什么注释掉的是vmTemplates 而不是self 像其他的一样?
  • vmTemplates 是保存模型的变量,self 是对模型中“this”的引用,因此我使用哪个版本无关紧要。

标签: knockout.js


【解决方案1】:

你试过了吗:

ko.mapping.fromJS(template,self.selectedTemplate);

?

【讨论】:

    【解决方案2】:

    试着推一下

    // data comes from AJAX call response (entity from db)
    var template = ko.mapping.fromJS(data);
    
    if (isAddMode) {
        self.selectedCategory().EmailTemplates.push(template);
        self.selectedTemplate(template);
    } else {
        // why can't this work?!?
        //vmTemplates.selectedTemplate(template);                   
    
        // try it!
        self.selectedTemplate.Push(template);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多