2013-07-02 31 views
3

我有一个对象(analysisLogData),我使用它来使用KnockoutJS生成表。下面是一个包含此对象的视图模型:KnockoutJs - 推送到可观察数组中的元素不起作用

function AppViewModel() { 
    var self = this; 
    self.analysisLogData = ko.observableArray(); 
    self.analysisLogTitle = ko.observable("Warnings") 

    self.changeAnalysisLog = function(title) { 
     self.analysisLogTitle(title) 
    } 

    var data = 

    { 
     "Warnings": [ 
      { 
       "number": 3002, 
        "description": "There may be a problem with the device you are using if you use the default profile" 
      }, 

      { 
       "number": 3001, 
        "description": "There may be a problem with the device you are using if you don't use the default profile" 
      } 

      ] 

     , 
      "Errors": [ 
      { 


       "number": 1000, 
        "description": "No networks are loaded" 
      }, 

      { 
       "number": 1002, 
        "description": "No devices are loaded" 
      }] 




    } 


    self.addLog = function (type, content) { 
     self.analysisLogData()[type].push(content); 
    } 

    self.analysisLogData.push(data) 


} 

ko.applyBindings(new AppViewModel()); 

你可以在这里看到的结果是在一个的jsfiddle:http://jsfiddle.net/etiennenoel/V4r2e/5/

我希望能够增加一个错误或警告,而不会丢失的警告或错误已经存在。

我试图做的self.addLog功能如下:

self.addLog = function (type, content) { 
     self.analysisLogData()[type].push(content); 
    } 

,但它说,它不能推到一个未定义的对象...

回答

2

好,在拨弄玩耍后。我相信您需要对如何在可观察数组中推送数据进行一些更改。但是,如果不做大量修改,请在此链接中查看我的解决方案。

jsfiddle example

self.addLog = function (type, content) { 

    self.analysisLogData()[0][type].push({ 
     "number": 1002, 
     "description": content 
    }); 
} 

和数据对象应该是

"Warnings": ko.observableArray([........]), 
"Errors": ko.observableArray([..........]) 

我做了两件事

  1. 修改警告&错误是可观察到的阵列
  2. 我把DAT在此self.analysisLogData(一)[0] [类型] .push代替self.analysisLogData()【类型】.push
+0

谢谢,这样做! – CoachNono

0

self.analysisLogData()是包含数组的数组错误/警告。

我不确定您是否希望您的数据结构化。

为了让拨弄工作,你可以用这个代替addLog功能:

self.addLog = function (type, content) { 
     self.analysisLogData()[0][type].push(content); 
    } 
+0

是的,这是我多么希望我的数据结构。当我把你的代码,我可以添加一个元素。但是,表格没有得到更新:http://jsfiddle.net/etiennenoel/V4r2e/8/ – CoachNono

+0

当您执行analyzeLogData()与您要插入底层数组的parans时,这通常是您想要做的它。但是,您必须启动通知才能让订阅者知道可观察数据有新数据。见http://www.knockmeout.net/2012/04/knockoutjs-performance-gotcha.html。我通常在推送到数组后调用.valueHasMutated() –

相关问题