自定义绑定无法从Knockout 2.3更新到3.3 [英] Custom Binding not working updating from Knockout 2.3 to 3.3
问题描述
我的Windows 8.1应用程序在Knockout 2.3上工作正常,但更新到3.3后,似乎我在自定义绑定中收到错误的上下文。
My Windows 8.1 App was working fine on Knockout 2.3 but after updating to 3.3 it seems like I get the wrong Context in my custom binding.
我在应用程序的命令栏中对各个元素应用绑定:
First here is how I apply binding for individual elements in the command bar of my app :
var cmdArray = [];
var commandIsRunning = function() {
return _.any(cmdArray, function(command) {
return command.isRunning();
});
};
_.each(_bottomCommands, function (row) {
if(row.command) {
// command wrapper
var commandWrapper = ko.command({
action: function() {
var rowCommand = row.command();
if (rowCommand) {
return rowCommand();
}
return WinJS.Promise.as();
},
canExecute: function() {
var rowCommand = row.command();
if (rowCommand) {
return rowCommand.canExecute() && !commandIsRunning();
}
return false;
}
});
cmdArray.push(commandWrapper);
//Bind the command
var element = document.querySelector('#' + row.id);
if (element) {
element.setAttribute('data-bind', 'command: $data');
ko.applyBindings(commandWrapper, element);
}
}
});
这是我的自定义绑定代码
Here is my custom binding code
ko.bindingHandlers.command = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var command = ko.utils.unwrapObservable(valueAccessor());
ko.bindingHandlers.click.init.call(this, element, ko.observable(command), allBindingsAccessor, viewModel, bindingContext);
},
update: function (element, valueAccessor, allBindingsAccessor) {
var command = ko.utils.unwrapObservable(valueAccessor());
ko.bindingHandlers.enable.update.call(this, element, command.canExecute, allBindingsAccessor);
}
};
问题出在:
ko.bindingHandlers.enable.update.call(this, element, command.canExecute, allBindingsAccessor);
canExecute
是未定义的,我认为是因为我没有在 init
和更新
处理程序中获得正确的上下文。那么我在代码中做错了什么?再次,代码在Knockout 2.3中工作,所以可能是一个Knockout问题?
canExecute
is undefined which I think is because I am not getting the right context in the init
and update
handlers. So what am I doing wrong in my code? Again the code was working in Knockout 2.3 , so could it be a Knockout issue?
更新:
我创建了jsFiddle来显示问题。它包含 ko.command
的定义,因为我认为这可能是问题的原因
JSFiddle
UPDATE:
I created jsFiddle to show the problem. It contains the definition for ko.command
because I thought that could be the cause of problem
JSFiddle
推荐答案
错误是因为Knockout 3.x绑定功能不同。在2.x中,您可以直接绑定到一个函数,但在3.x中,Knockout调用该函数来获取viewmodel。您仍然可以绑定到Knockout 3.x中的一个函数,但是您需要将其包装在可观察的或另一个函数中。
The error is caused because Knockout 3.x binds to functions differently. In 2.x, you could bind directly to a function, but in 3.x, Knockout calls the function to get the viewmodel. You can still bind to a function in Knockout 3.x, but you'll need to wrap it in an observable or in another function.
ko.applyBindings(function() { return commandWrapper }, element);
https://jsfiddle.net/mbest/nrb97g7e/38/
这篇关于自定义绑定无法从Knockout 2.3更新到3.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!