Knockoutjs shoot event after every modification in UI or model

Asked

Viewed 119 times

0

Hello, as you would intercept changes in the UI or model that were made sensitizing the knockout?

Using the subscribeI know there was a change in a property, but what if I had 100 models, with 10 properties each? I wanted to intercept whichever change in whichever model.

I tried to use the ko.bindingProvider.instance.preprocessNode (http://knockoutjs.com/documentation/binding-preprocessing.html) but I was unsuccessful.

Another interesting thing to achieve, in case you use the ko.bindingProvider.instance.preprocessNode is to know if it is the first time the event has been triggered, perhaps by adding an attribute to the element associated with the node that is passed as parameter to the function.

Example:

function Modelo() {

  var self = this;
  self.Nome = ko.observable();
  
  self.Nome.subscribe(function() {alert('Houve mudança, mas e se eu tivesse 100 modelos, com 10 propriedades cada?');});
  
  self.mudaNome = function() { self.Nome("Novo Nome");}
}

$(function() {
  ko.applyBindings(new Modelo());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>
  <input type="text" data-bind="value:Nome" placeholder="Seu nome aqui" />
  <br />
  <strong>Seu nome é: <span data-bind="text:Nome"></span>
    <br />
    
    <button data-bind="click:mudaNome">Novo Nome</button>
    
</strong>
</div>

Has anyone ever done anything like this? I therefore need to know:

  • When a change in the model is about to happen or happened, regardless of ownership, more or less like I do using the subscribe with "beforeChange" and "change".
  • When a change in the UI (DOM) is about to happen or happened because of a user interaction in a knockout model, more or less like with the MutationObserver (documentation here). Changes because of other frameworks don’t need to be captured.
  • 1

    Have you tried using the knockout validation plugin

  • @Guto I’ve used the plugin but not for that purpose. I’ll investigate it to see if I have any insight! Thanks!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.