0

我对我的代码有 2 个问题:

为什么输入图像被禁用(悬停时没有手形光标)但是当 TreeDiv 有任何元素(树存在)并且选择了一个节点时,输入图像仍然被禁用。它没有启用。

为什么这个?

我还想知道为什么我需要 viewmodel 实例,它无处使用......(这是作者网站的代码)

<input type="image" id="CreateSiblingUnit" data-bind="value: selectedUnit,enable: isUnitSelected"  src="~/Content/Images/unitaddsibling.png" title="Create sibling unit"  data-url="@Url.Action("CreateSibling", "Unit")" />

var viewModel = {
                isUnitSelected: ko.observable(false),
                selectedUnit: $('#TreeDiv').children().length > 0 && $("#TreeDiv").dynatree("getActiveNode") != null
            };

ko.applyBindings(viewModel);
4

1 回答 1

2

In your view model,

isUnitSelected: ko.observable(false),

defines isUnitSelected as an observable with an initial value of false, but I can't see anything that would ever set it to true. Your binding (enable: isUnitSelected) will therefore cause it to be disabled until something alters the value of isUnitSelected.

I'm a bit confused by your two properties in the view model. The first will always be false, and the second will be a boolean, so the name "selectedUnit" doesn't make much sense.

I'm not sure what dynatree is, but I'd imagine you probably need to bind to some kind of event (when a node is selected etc), and set the properties in your view model accordingly. E.g.

// In your view model:
isUnitSelected: ko.observable(false),
selectedUnit: ko.observable()

// In some event handler, update the view model's properties each time a node is clicked
var hasNodes = ($('#TreeDiv').children().length > 0);
var activeNode = null;
if (hasNodes) {
    activeNode = $("#TreeDiv").dynatree("getActiveNode");
}
selectedUnit(activeNode);
isUnitSelected(hasNodes && activeNode !== null);

The viewModel is used in the line:

ko.applyBindings(viewModel);

In this case your viewModel is just a basic Javascript object. You could also use the slightly more complex (but ultimately more useful) syntax like so, which would allow you to create an instance of a view model "object":

var ViewModel = function() {
    var self = this;

    self.isUnitSelected = ko.observable(false);
    //...
}

ko.applyBindings(new ViewModel());
于 2013-01-06T00:17:03.237 回答