knockoutjs获取输入值并在单击按钮时将值传递给另一个数组名称

时间:2014-09-18 11:21:27

标签: knockout.js

我的请求是,点击一个按钮,如何获取输入字段的值(id =" inputCustomViewName")并用它来命名视图?

HTML:

    <div class="rowStyle01">
                        <label>Define a new custom view</label>
                        <div class="inputStyle03">
                            <input type="text" id="inputCustomViewName" placeholder="Enter a name for your customer view" />
                        </div>
                    </div>
<div class="buttonStyle03 buttonStyle03Ext01 columnRight" data-bind="click: myParentViewModel.addNewCustomView">
            <a>Save</a>
        </div>

JS:

function ParentViewModel()
{
    var that = this;
    that.myViewModelRibbon = new TabViewModel();

    that.addNewCustomView = function (data, event) {
        var allSubTAbs = data.myViewModelRibbon.ActiveSubTabs();
        var newSubTab = {
            "SubTabName": "sample text", // how to get this name from text box ?
            "IconPath": "images/icons/Document.png",
            "GroupID": "0",
            "IsMultipleActive": "0",
            "EnabledState": "enabled",
            "CallbackOnSelect": "openCommonForm"
        };
        data.myViewModelRibbon.ActiveSubTabs.push(newSubTab);

    }
    return that;
}

var myParentViewModel = new ParentViewModel();
ko.applyBindings(myParentViewModel);

现在当我点击&#34; Save&#34;按钮只有&#34; SubTabName&#34;:&#34;示例文本&#34;每次都在myViewModelRibbon上推送,而我想要输入值,无论我们输入什么,它应该推送到视图模型......怎么样?任何溶解?

1 个答案:

答案 0 :(得分:1)

向ParentViewModel添加一个字段并将其绑定到输入框。 只要输入值发生变化,就会更新绑定字段。这正是应该使用淘汰赛的地方。

...
<input type="text" id="inputCustomViewName" 
       placeholder="Enter a name for your customer view"
       data-bind="value: myParentViewModel.tabName" /> 
...


function ParentViewModel()
{
    var that = this;
    that.tabName = ko.observable(); // <- new field (observable)
    that.myViewModelRibbon = new TabViewModel();

    that.addNewCustomView = function (data, event) {
        if (that.tabName() != null && that.tabName() !== '') { 
            var allSubTAbs = data.myViewModelRibbon.ActiveSubTabs();
            var newSubTab = {
                "SubTabName": that.tabName(), // <--
                "IconPath": "images/icons/Document.png",
            ...
        }
    }