knockout.js-ko没找到

时间:2012-07-13 08:25:31

标签: knockout.js

这是我的js文件:

function AppViewModel() 
{
    this.firstName = ko.observable("Bert");
    this.lastName = ko.observable("Bertington");
}
ko.applyBindings(AppViewModel());

这是我的html文件:

<html>
<head>
    <script type='text/javascript' src='ko.js'></script>
    <script type='text/javascript' src='knockout-2.1.0.debug.js'></script>

</head>
<body>
    <p>First name: <strong data-bind="text: firstName"></strong></p>
    <p>Last name: <strong data-bind="text: lastName"></strong></p>

    <p>First name: <input data-bind="value: firstName" /></p>
    <p>Last name: <input data-bind="value: lastName" /></p>
</body>
</html>

未捕获的ReferenceError:未定义ko

有人可以帮我这个吗?

提前致谢

3 个答案:

答案 0 :(得分:8)

尝试颠倒JavaScript文件的顺序 -

<script type='text/javascript' src='knockout-2.1.0.debug.js'></script>
<script type='text/javascript' src='ko.js'></script>

我怀疑ko.js文件在主要&#39;淘汰赛中定义之前正试图访问ko个对象。 js文件。

答案 1 :(得分:0)

我的解决方案是按照上面的顺序放置我的ko脚本,并在文档加载了JQuery(或等效的)文档就绪函数后执行任何ko.xyz代码。 e.g。

 $(document).ready(function(){
            var model = new ReviewersViewModel();
            ko.applyBindings(model);

            $('.datetimepicker_mask').datetimepicker({
                mask: '9999/19/39 29:59'
            });

            ko.bindingHandlers.datetimepicker = {
                init: function (element, valueAccessor, allBindingsAccessor) {
                    //initialize datepicker with some optional options
                    var options = allBindingsAccessor().datetimepickerOptions || {};
                    $(element).datetimepicker(options);

                    //handle the field changing
                    ko.utils.registerEventHandler(element, "change", function () {
                        var observable = valueAccessor();
                        try {
                            observable($(element).datetimepicker("getDate"));//****
                        }
                        catch (ex) { }
                    });

                    //handle disposal (if KO removes by the template binding)
                    ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                        $(element).datetimepicker("destroy");
                    });

                },
                update: function (element, valueAccessor) {
                    var value = ko.utils.unwrapObservable(valueAccessor()),
                        current = $(element).datetimepicker("getDate");

                    if (value - current !== 0) {
                        $(element).datetimepicker("setDate", value);
                    }
                }
            };
        });

答案 2 :(得分:0)

定义脚本,它是Knockout js库,它包含已淘汰的预定义方法。