2013-07-02 34 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() –

相關問題