0
votes

I found a custom binding that makes an observable update in an editable div. I'm not able to run a function when an event occurs with it.

Does anyone know what I can do to my custom binding "editableText" run a function in my ViewModel?

I would like the function "nameChange" to run when text is changed.

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/

1
I'm afraid your question might be a dupe of this one: there are no (widely supported) events for ContentEditable elements.Jeroen
Check out this Kendo UI binding, its really nice if you need a KO enabled HTML editor rniemeyer.github.io/knockout-kendo/web/Editor.htmlAnders

1 Answers

0
votes

How about subscribing to changes on the observable? (Look at explicitly subscribing to observables)

self.firstNameSubscription = self.firstName.subscribe(function (newValue){
  //do something
});

If you do this you need to dispose of the subscription when your view model goes down

self.firstNameSubscription.dispose();

If you want the observable to be updated every time a key is entered have a look here

My personal opinon is that using the variable name 'self' is probably a bad idea...