Knockout绑定不适用于jsTree

时间:2013-01-29 20:34:54

标签: binding knockout.js jstree

我正在努力让jsTree(1.0-rc3)使用Knockout.js(2.2.1)。

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

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

运行小提琴并浏览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);

1 个答案:

答案 0 :(得分:2)

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

尝试执行以下操作:
变化:
window.ServerViewModelInstance.Server = ko.mapping.fromJS(response);
到:
window.ServerViewModelInstance.Server(response);

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

并在视图中绑定到observables .. 例如,而不是:
... "value: Server.ServerName, ...
将其更改为: ... "value: Server().ServerName, ...
(例如在访问财产之前执行该功能)
当单击树中的新服务器名称节点时,它可以工作并更新表单(在firefox中尝试过)
可以在以下位置找到包含修改后代码的示例副本:http://jsfiddle.net/RZ92g/2/