0

我正在尝试让 jsTree (1.0-rc3) 与 Knockout.js (2.2.1) 一起使用。

参见示例 jsFiddle:http: //jsfiddle.net/adeconsulting/qfr6A/

注意:我在 Fiddle 中包含了几个 JS 资源,以尽可能接近我的 Visual Studio 项目,以防可能导致此问题的库之间存在冲突。

运行 Fiddle 并浏览 jsTree,它是按物理位置和类型列出的服务器列表。它有助于打开 Firebug 的控制台,这样您就可以看到 ajax 调用和响应。单击叶节点时,将进行 ajax 调用以检索服务器详细信息并显示其值使用 Knockout 绑定的表单。选择非叶节点时隐藏表单。

它在您第一次单击叶节点时起作用。之后,Knockout 不会更新叶节点点击的表单。但是,如果您碰巧单击了“编辑”按钮,则会突然显示最新的服务器详细信息。

我认为 jsTree 和 Knockout 绑定之间存在冲突,但不知道从哪里开始解决可能的问题。

由于 stackoverflow 显然需要至少一个代码块,这里是 Fiddle 的 JavaScript 部分:

// Global vars:
var prevJsTreeNodeId = null;
var serverModelBindingsApplied = false;
var serverLoadInProgress = false; 

/*
 * The knockout.js view model
 */
var ServerViewModel = function () {
    // Data
    var self = this;
    self.IsReadOnly = ko.observable(true);       // the form's input mode
    self.btnEditSave = ko.observable("Edit");    // the Edit/Save button text
    self.Server = ko.observable({});             // the Server object

    // Operations
    self.setEditable = function () {
        self.IsReadOnly(false);
        self.btnEditSave("Save");
    };

    self.setReadOnly = function () {
        self.IsReadOnly(true);
        self.btnEditSave("Edit");
    };

    self.doEditSave = function () {
        var flag = self.IsReadOnly();
        if (flag) {
            // switch to Edit mode
            self.setEditable();
        }
        else {
            // switch back to readOnly
            self.setReadOnly();
        }
    };

    // use ajax to update the knockout.js view model's Server object for the specified server name
    self.load = function (serverName) {
        if (!serverLoadInProgress) {
            serverLoadInProgress = true;
            // use ajax to retrieve the server's details
            var data = {
              json: JSON.stringify({
                   ServerName: serverName,
                   PrimaryIP: "1.2.3.4",
                   BrandDesc: "Dell",
                   OSDesc: "Windows 2003 Server",
                   Location: "xyz"
              }),
              delay: 1
            };
            $.ajax({
                url:"/echo/json/",
                data:data,
                type:"POST",
                success:function(response)
                {
                   console.log(response);
                   window.ServerViewModelInstance.Server = ko.mapping.fromJS(response);
                   // apply bindings the first time we retrieve a Server object
                   if (!serverModelBindingsApplied) {
                      ko.applyBindings(window.ServerViewModelInstance,
                                       document.getElementById('servercontent'));
                      serverModelBindingsApplied = true;
                   }  
                   else {
                     // hmmm... updating the view model's .Server property doesn't trigger the 
                     //  form to be updated, yet if we click the Edit button, the new values
                     //  suddenly appear, so try emulating that here...
                     self.setReadOnly();
                   }
                }
            });

           serverLoadInProgress = false;
        }
    };
};    // ServerViewModel

/*
 * document load 
 */
$(function () {
    // configure the jsTree
    $("#divtree")
      .jstree({
          "themes": { "theme": "default", "dots": true, "icons": true },
          "plugins": ["themes", "html_data", "ui", "types"],
          "types": {
              "type_attr": "tag",   // the attribute which contains the type name
              "max_depth": -2,      // disable depth check
              "max_children": -2,   // disable max children check
              "valid_children": ["root"],
              "types": {
                  "root": {
                      "valid_children": ["level1"]
                  },
                  "level1": {
                      "valid_children": ["level2"],
                      "start_drag": false,
                      "move_node": false,
                      "delete_node": false,
                      "remove": false
                  },
                  "level2": {
                      "valid_children": ["leaf"],
                      // use the theme icon for the level2 nodes
                      "start_drag": false,
                      "move_node": false,
                      "delete_node": false,
                      "remove": false
                  },
                  "leaf": {
                      "valid_children": "none"
                  }
              }
          }
      });

    // register to receive notifications from #divtree when a jsTree node is selected
    $("#divtree").bind("select_node.jstree", function (event, data) {
          // data.rslt.obj is the jquery extended node that was clicked
          var key = data.rslt.obj.attr("key");
          var id = data.rslt.obj.attr("id");
          if (id == prevJsTreeNodeId) {
              // user clicked the same node, nothing to do
              return;
          }
          prevJsTreeNodeId = id;

          // when a jsTree node is selected, reset the knockout.js view model to read only
          window.ServerViewModelInstance.setReadOnly();

          var idx = key.indexOf("Server");
          if (idx === 0) {  // "Server|servername"
              // show the "servercontent" div
              $("#servercontent").show();
              // display the server details
              var serverName = key.substr(idx + 7, key.length);
              window.ServerViewModelInstance.load(serverName);
          }
          else {
              // hide the "servercontent" div
              $("#servercontent").hide();
          }
      });


    // hide the "servercontent" div
    $("#servercontent").hide();

    // instantiate the knockout.js view model
    window.ServerViewModelInstance = new ServerViewModel();
});  // document ready

// initialization timer routine to select the main jsTree node
setTimeout(function () {
    // open the root node
    $.jstree._reference("#divtree").open_node("#root");
}, 500);
4

1 回答 1

2

对不起,我在下面的错误格式 - 这个编辑器不是我的朋友...... :-/
如果我理解正确,点击的树节点的详细信息面板没有使用正确的数据更新 - 对吗?

尝试执行以下操作:将:
更改
window.ServerViewModelInstance.Server = ko.mapping.fromJS(response);
为:
window.ServerViewModelInstance.Server(response);

(例如,不覆盖您只绑定一次的初始 ko.observable,而是更新其值)

并查看您绑定到可观察对象的位置..例如,而不是:
... "value: Server.ServerName, ...
将其更改为:(
... "value: Server().ServerName, ...
例如,在访问属性之前执行该函数)
它可以在单击树中的新服务器名称节点时工作并更新表单(已尝试firefox)
可以在以下位置找到带有修改后代码的示例副本:http: //jsfiddle.net/RZ92g/2/

于 2013-01-29T22:13:20.443 回答