我找到了一个自定义绑定,可以在可编辑的 div 中进行可观察的更新。当事件发生时,我无法运行函数。
有谁知道我可以对我的自定义绑定“editableText”做些什么在我的 ViewModel 中运行一个函数?
我希望函数“nameChange”在文本更改时运行。
HTML:
<div contenteditable="true" data-bind="event: { change: nameChange }, editableText: firstName"></div>
Javascript:
//Editable Text Custom Binding
ko.bindingHandlers.editableText = {
init: function (element, valueAccessor) {
$(element).on('blur', function () {
var observable = valueAccessor();
observable($(this).text());
});
},
update: function (element, valueAccessor, allBindingsAccessor, data) {
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).text(value);
}
};
//Knockout ViewModel
function viewModel(){
var self = this;
self.firstName = ko.observable();
self.status = ko.observable();
self.nameChange = function(){
console.log("Name has been updated");
ko.mapping.fromJS("Name has been updated", {}, self.status)
}
self.loadName = function(){
ko.mapping.fromJS("hey", {}, self.firstName)
}
}
var vm = new viewModel();
ko.applyBindings(vm);
vm.loadName();
JSFIDDLE:http: //jsfiddle.net/madscientist1882/urLd2/