Knockout.js点击不触发jQuery Steps Plugin

时间:2016-03-07 15:35:51

标签: knockout.js jquery-steps

我使用jQuery Steps plugin创建向导,在第二步,您将添加1 .. *字段,这是一个JSON对象数组,将被发布到服务器。我正在尝试使用Knockout来显示每个字段名称的输入。

单击时,应将新的空字段推送到数组,并显示文本框。但是,在表单/ jquery步骤中,addField函数不会触发。如果我把它拿出来,它确实如此。有没有办法阻止jQuery步骤干扰绑定?这是代码的精简版本:

function AppViewModel() {
    var self = this;
    self.fields = ko.observableArray([]);
    self.addField = function() {
        // push field to self.fields
    }

}
ko.applyBindings(new AppViewModel());

// jQuery Steps
var form = $("#stepsForm");

form.children("div").steps({
    headerTag: "h3",
    bodyTag: "section",
    transitionEffect: "slideLeft",
    stepsOrientation: "vertical"
});
table {
  border: 1px solid blue;
}
td {
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-steps/1.1.0/jquery.steps.min.js"></script>
 
<form id="stepsForm" action="#" novalidate>
    <div class="form-container">
        <h3>Section1</h3>
        <section>
            <table class="table table-condensed">

                <tr data-bind="foreach: fields">
                    <td>
                        <div data-bind="text:FieldName"></div>test
                    </td>
                </tr>
            </table>

            <button data-bind="click: addField">Add another</button>

        </section>
    </div>
</form>

1 个答案:

答案 0 :(得分:0)

这个问题归结为JavaScript执行的时间。由于我正在使用服务器数据来加载Knockout对象(没有ajax),这很复杂。这是我终于上网的地方:

我的JavaScript按此顺序加载:

  1. jQuery,jQuery步骤,Knockout等(捆绑)
  2. 视图的JavaScript文件
  3. 嵌入在视图中的内联JavaScript
  4. #2 - 视图的JavaScript文件(例如fields.js)

    $(document).ready(function () {
    
        var form = $('#stepsForm');
    
        form.children("div").steps({
            headerTag: "h3",
            bodyTag: "section",
            transitionEffect: "slideLeft",
            stepsOrientation: "vertical"
        });
    });
    

    #3 - 视图中的嵌入式JavaScript(例如fields.html)

    <script>
        function AppViewModel() {
            var self = this;
            self.fields = ko.observableArray([]); 
            self.addField = function () {
                // push field to self.fields
            }
        }
        $(document).ready(function () {
            //Used MVC Razor engine to load some other server data into other KO objects here. (omitted for clarity)
            ko.applyBindings(new AppViewModel());
    
        })
    
    </script>