2013-04-15 62 views
0

我似乎在奮力綁定到對象上的點擊,我想不通爲什麼。我的HTML片段如下:淘汰賽:綁定到值上點擊

 <div class="moodControlGroup"> 
     <label class="control-label" for="nodeHeight">Height</label> 
      <div class="controls"> 
       <input type="text" class="query" id="nodeHeight" data-bind="value: settings.nodes.height.value" /> 
       <textarea class="queryExpanded funcText" data-bind="value: settings.nodes.height.funcValue"></textarea> 
      </div> 
      <input class="fx btn btn-primary" type="submit" value="fx" data-bind="click: function(item) { alert(JSON.stringify(item)) ; }, css: { selected: settings.nodes.height.isFunc }" /> 
    </div> 

我的問題在於我的提交按鈕在底部。該設置具有以下JSON結構 - 這是使用變成了淘汰賽對象ko.mapping:

nodes: { 
       width: { isFunc: false, value: 24, funcValue: "" }, 
       height: { isFunc: true, value: 24, funcValue: "function(d) { return d.dy; }" }, 
}... 

我想要做的就是點擊提交按鈕,並得到高度對象:

height: { isFunc: true, value: 24, funcValue: "function(d) { return d.dy; }" } 

看來不過我只得到了空對象{},或者對象小幅上漲,其包含的節點屬性。我如何設法定位我的點擊事件以獲取正確的值?最終,我希望能夠切換它後面的isFunc值的狀態,以更新一些CSS ...但我不希望使用複選框控件。

任何人都可以建議我可能是做錯了什麼?

感謝

+0

我們能看到你的.applyBindings打電話? – BrandonLWhite

+0

@LatencyMachine:對不起,我應該包括這一點。我現在沒有代碼來處理,但是應用綁定需要一個ViewModel。 ViewModel有一個設置對象,然後又有節點。所以看起來像ViewModel:{Settings:{Nodes:{...}}}作爲JSON對象。 – Ian

回答

1

您需要創建KO背景下,如果你想利用在單擊處理「這個」值。既然你沒有迭代一個集合(foreach),然後嘗試使用'with'綁定,比如在外部div中,或者如果你只是想快速嘗試,在提交按鈕周圍扔一個wrapper div,並且綁定數據與此。

事情是這樣的:

<div data-bind="with: settings.nodes.height"> 
    <input class="fx btn btn-primary" type="submit" value="fx" data-bind="click: function(item) { alert(JSON.stringify(item)) ; }, css: { selected: isFunc }" /> 
</div> 

我不知道你的最終代碼會看起來像,但如果所有你曾經打算在這塊做的是綁定到settings.nodes.height ,那麼很可能你會想把'with:settings.nodes.height'放在最外面的div上。然後,您可以將所有後代綁定僅縮減爲高度對象內的屬性。就像這樣:

<div class="moodControlGroup" data-bind="with: settings.nodes.height"> 
     <label class="control-label" for="nodeHeight">Height</label> 
      <div class="controls"> 
       <input type="text" class="query" id="nodeHeight" data-bind="value: value" /> 
       <textarea class="queryExpanded funcText" data-bind="value: funcValue"></textarea> 
      </div> 
      <input class="fx btn btn-primary" type="submit" value="fx" data-bind="click: function(item) { alert(JSON.stringify(item)) ; }, css: { selected: isFunc }" /> 
    </div> 

更新:之後,我們在評論簡短的討論,我決定你的代碼粘貼到的jsfiddle。

This fiddle在外部div上不使用'with'綁定,因此根ViewModel是點擊處理程序的'this'綁定的內容(這聽起來像你不想要的)。我添加了一個'fx2'按鈕,它將使用ko.mapping.toJSON轉儲'this'。正如評論中所討論的那樣,JSON.stringify將不會顯示您的可觀察屬性,這些屬性實際上是此時的函數。

This other fiddle引入了一個數據綁定= 「用:settings.nodes.height」 關於外層div。因此,點擊處理程序的'this'現在引用了settings.nodes.height對象,我相信這是你想要的。

+0

感謝您的答案LatencyMachine,我實際上嘗試使用一個,但警告兩個項目(函數的第一個參數)的JSON'ified版本和'這'留給我一個空對象'{}',所以我無法訪問值/ isFunc等進行編程。 – Ian

+0

我明白了。也許這會有所幫助:請記住,'this'將它的所有屬性當作可觀察對象 - 這意味着它們都是函數。也許這就是爲什麼你看到「對象{}」或任何你的警報。 – BrandonLWhite

+0

後續步驟:因此,請使用ko.toJSON(this)來創建轉儲字符串,而不是使用JSON.stringify。 – BrandonLWhite