我已经阅读了关于此的所有相关帖子,花了两天时间试图找出我在这里做错了什么而没有取得多大成功。
在这里使用这个JS小提琴作为例子:http://jsfiddle.net/rniemeyer/dtpfv/我试图实现一个脏标志。唯一的区别是我正在更改常规范围内的数据与输入字段,并使用映射插件与手动分配可观察对象。
$(document).ready(function(){
ko.dirtyFlag = function(root, isInitiallyDirty) {
var result = function() {},
_initialState = ko.observable(ko.toJSON(root)),
_isInitiallyDirty = ko.observable(isInitiallyDirty);
result.isDirty = ko.computed(function() {
return _isInitiallyDirty() || _initialState() !== ko.toJSON(root);
});
result.reset = function() {
_initialState(ko.toJSON(root));
_isInitiallyDirty(false);
};
return result;
};
$.getJSON('/environments/data.json', function(jsondata) {
var mapping = {
create: function (options) {
var innerModel = ko.mapping.fromJS(options.data);
for (var i=0; i < innerModel.deployments().length; i++) {
innerModel.deployments()[i].dirtyFlag = new ko.dirtyFlag(innerModel.deployments()[i]);
}
return innerModel;
}
}
var viewModel = ko.mapping.fromJS(jsondata, mapping);
self.save = function() {
console.log("Sending changes to server: " + ko.toJSON(this.dirtyItems));
};
self.dirtyItems = ko.computed(function() {
for (var i = 0; i < viewModel().length; i++ ) {
return ko.utils.arrayFilter(viewModel()[i].deployments(), function(deployment) {
return deployment.dirtyFlag.isDirty();
});
}
}, viewModel);
self.isDirty = ko.computed(function() {
return self.dirtyItems().length > 0;
}, viewModel);
self.changeTag = function (data, event) {
// Neither .change() nor .trigger('change') work for me
$(event.target).parents().eq(4).find('span.uneditable-input').text(data.tag).change()
// This value never changes.
console.log('Dirty on Change: '+self.dirtyItems().length)
}
ko.applyBindings(viewModel);
});
})
这是HTML的一部分,它触发changeTag()
函数,用下拉菜单中的选项替换current_tag()
。但是,这不会触发KnockoutJS更新。
<div>
<span data-bind="text: current_tag() }"></span>
<div>
<button data-toggle="dropdown">Select Tag</button>
<ul>
<!-- ko foreach: $.parseJSON(component.available_tags() || "null") -->
<li><a href="#" data-bind="click: function(data, event) { changeTag(data, event) }"></a></li>
<!-- /ko -->
</ul>
</div>
</div>
我正在尝试解决这个问题的第二天。知道我在这里做错了什么吗?我应该使用输入字段而不是常规的span元素吗?我是否需要直接更改值viewModel
而不是使用jQuery来操作DOM? (我实际上已尝试过,但更改viewModel
然后重新绑定到它似乎会减慢速度,除非我做错了)
谢谢。
答案 0 :(得分:3)
正如评论中所述,它被认为是糟糕的淘汰赛实践&#39;通过jQuery更新值,当您还可以直接更新observable时。 Knockout促进了数据驱动的方法。
回复您的上一条评论(尚不确定如何回答有关堆栈溢出的评论):UI未获取更改的原因是您分配的值错误:
var x = ko.observable(1); // x is now observable
x = 3; // x is no longer observable. After all, you've assigned the value 3 to it. It is now just a number
x(3); // this is what you're after. x is still an observable, and you assigned a new value to it by using Knockout's parentheses syntax. If x is bound to the ui somewhere, you'll see the value 3 appear
所以你想做
jsondata[environment()].deployments[deployment()].current_tag(ko.dataFor(event.target).tag);