2013-08-28 89 views
0

我有一個示例,我試圖檢測選定元素的文本值並將其填充到彈出窗口中。我知道如何使用jQuery來做到這一點,但我不想將Ui意識帶入視圖模型。我知道我錯過了一些簡單的東西,但是有人可以解釋我需要做什麼來綁定UI中選定元素的文本值,並將其綁定到Knockout中的另一個可觀察元素。如何基於選定/單擊元素設置可觀察值

全部工作JsFiddle

減這裏的CSS是HTML和JS,我已經迷上了迄今爲止

<ul data-bind="foreach: items"> 
    <li class="divContainer"> <span title="filename" class="tbox" data-bind="text: name, click: $root.openControl "></span> 
<span title="description" class="tbox" data-bind="text: description"></span> 

    </li> 
</ul> 
<div id="nameDiv" class="nameContainer"> <span class="smallTitle"></span> 

    <input type="textbox" class="mytextbox" data-bind="value: currentField" /> 
    <input type="button" id="SaveChange" class="editbtn" value="&#x2714;" /> 
    <input type="button" id="CancelChange" class="editbtn" value="&#x2716;" /> 
</div> 

JS

var Item = function (name, description) { 
    this.name = ko.observable(name); 
    this.description = ko.observable(description); 
} 

    function myViewModel() { 
     var self = this; 
     //sample list of items 
     self.items = ko.observableArray([ 
     new Item('item 1', ' item 1 Description'), 
     new Item('item 2', 'item 2 Description'), 
     new Item('item 3', 'Report3 Description'), 
     new Item('item 4', 'Report4 Description')]); 

     //observable fields 
     self.currentField = ko.observable(""); 

     //bind current item text to field 
     self.openControl = function() { 
      self.currentField($(this)); ///Here I need to pick up the text of the item that was clicked on 
     }; 
    }; 

ko.applyBindings(new myViewModel()); 

function positionDiv(x_pos, y_pos) { 

    var d = document.getElementById('nameDiv'); 
    d.style.display = 'none'; 
    d.style.position = 'absolute'; 
    d.style.left = x_pos + 'px'; 
    d.style.top = y_pos + 'px'; 
    $('#nameDiv').fadeIn('slow'); 
} 
$('.tbox').click(function() { 
    var myText = $(this); 
    var t = $(this).attr('title'); 
    if (t === 'filename') { 
     $('.smallTitle').text('Enter new filename'); 
    } else { 
     $('.smallTitle').text('Enter new description'); 
    } 
    displayEditBox(myText); 
}); 


function displayEditBox(myText) { 

    //determine middle of span element 
    var offset = myText.offset(); 
    var width = myText.width(); 
    var height = myText.height(); 
    var centerX = offset.left + width + 5; 
    var centerY = offset.top - 10; 

    positionDiv(centerX, centerY); 
} 

$('#CancelChange').click(function() { 
    $('#nameDiv').fadeOut('fast'); 
    clearField($('.mytextbox')); 
}); 

function clearField(field_name) { 
    field_name.val(''); 
} 

由於提前,

回答

3

更改您的openControl函數的定義以採用參數ETER:

self.openControl = function (item) { 
    self.currentField(item.description()); 
}; 

這應該是點擊施加到,因爲在其中click結合由該位置的item(所述items數組的一個元素),數據上下文是foreach: items的本體結合。