对KnockoutJS脚本的多次引用打破了标准行为

时间:2013-03-05 19:47:24

标签: javascript jquery ajax knockout.js

例如,

  1. 我有KO已经注册的页面,并且有一个具有可观察属性“someProperty”的viewmodel;
  2. 我通过ko.isObservable(viewmodel.someProperty)检查“someProperty”是否是可观察属性 - 它返回'true';
  3. 我执行ajax调用以获取一些html标记,其中也注册了KO;
  4. 现在如果检查ko.isObservable(viewmodel.someProperty),它将返回false;
  5. 此外,手动添加的所有KO扩展都将丢失。它看起来像jQuery(http://bugs.jquery.com/ticket/10066)中的bug(或功能)。

    var viewModel = new function() {
                var self = this;
                this.serverData = {
                    Controller: ko.observable(null),
                    Enabled: ko.observable(false),
                    Id: ko.observable(null),
                    ParentId: ko.observable(null),
                    Title: ko.observable(null),
                    MaterialId: ko.observable(null),
                    Alias: ko.observable(null)
                };
                this.treeData = {
                    tree: ko.observable(null),
                    node: ko.observable(null)
                };
                this.submit = submit;
                this.cancel = cancel;
                this.openMaterials = menuOptions.openMaterials;
    }
    
    // ...
    var data = ko.utils.createUnobservable(viewModel.serverData);
    // ...
    
    (function(ko) {
        ko.utils = ko.utils || {};
    
        ko.utils.createUnobservable = function(observable) {
            var unobservable = {};
            (function() {
                for (var propertyName in observable) {
                    var observableProperty = observable[propertyName];
                    if (ko.isObservable(observableProperty) /* always 'false' after ajax */) {
                        unobservable[propertyName] = observableProperty();
                    }
                }
            })();
    
            return unobservable;
        };
    
    })(ko = ko || {});
    

1 个答案:

答案 0 :(得分:0)

您可以通过在包含加载的ajax之前保存ko全局变量的副本,然后在之后恢复它来解决此问题。

var savedKo = window.ko;
.... // do the ajax thing
window.ko = savedKo;