2012-02-26 39 views
11

如何使用knockout.js設置焦點被綁定到陣列中的模板創建一個元素?knockout.js將焦點設置在一個模板

我有綁定到一個表中,其中每一行是一組輸入元件,以允許陣列元素的屬性要被編輯的可觀察陣列。在底部是一個"Add"按鈕,將一個新元素插入到陣列中,創建輸入字段的一個新行。

我試圖做的是有"Add"按鈕被按下後,設置爲第一個新創建的輸入域的焦點。

HTML:

​​

的Javascript:

function Attribute(id, name, description, hardcoded) { 
    var self=this; 
    self.AttributeID=ko.observable(id || 0); 
    self.Name=name || ''; 
    self.Description=description || ''; 
    self.HardCoded=hardcoded || false; 
    self.nameFocus = true; 
} 

function AttributeSchema(attributeArray) { 
    var self=this; 

    // Properties 
    self.Attributes=ko.observableArray(attributeArray); 

    // Operations 
    self.addAttribute=function() { 
    self.Attributes.push(new Attribute()); 
    }; 

    self.removeAttribute=function() { 
    self.Attributes.remove(this); 
    }; 
} 

var vmSchema=new AttributeSchema(
    [ 
    new Attribute(5, 'FirstName', 'First Name', true), 
    new Attribute(6, 'LastName', 'Last Name', true), 
    new Attribute(7, 'Blah', 'Blah', false) 
    ] 
); 

ko.applyBindings(vmSchema); 

回答

19

目前,你有這樣的代碼:

<input type='text' data-bind='value: Name, disable: HardCoded' /> 

您可以嘗試添加屬性hasfocus: true

<input type='text' data-bind='value: Name, disable: HardCoded, hasfocus: true' /> 

請參見:http://knockoutjs.com/documentation/hasfocus-binding.html

+0

非常感謝,完美的答案! Knockout.js岩石! – Richard 2012-02-26 11:48:03

4

我在那裏的知名度是由複選框確定的領域,我想現場得到儘快成爲可見的焦點。使用默認的hasfocus綁定意味着只要失去焦點,該字段就會隱藏起來。

爲了解決這個我創建了一個 「單向」 hasfocus像這樣結合:

ko.bindingHandlers.koFocus = { 
    update: function (element, valueAccessor) { 
     var value = valueAccessor(); 
     var $element = $(element); 
      if (value()) { 
       $element.focus(); 
      } 
    } 
}; 

我然後代替:

data-bind="hasfocus: myObservable" 

與:

data-bind="koFocus: myObservable" 

問題解決

+1

我拆開valueAccessor這樣我就可以在通過myObservable()以及!'VAR值= ko.unwrap(valueAccessor());'然後,只需檢查'如果(值)',而不是'如果(值())' – 2014-11-12 19:52:29