Knockoutjs trigger event after any modification in the UI or the model

0

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

Using subscribe I know there was a change in a property, but what if I had 100 models, with 10 properties each? I wanted to intercept any change in any template.

I tried to use ko.bindingProvider.instance.preprocessNode ( link ) but I was not successful.

Another interesting thing to get, in case you use ko.bindingProvider.instance.preprocessNode is to know if this 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 a parameter to the function. / p>

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><scriptsrc="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 need, therefore, to know:

  • When a change in the model is about to happen or happened, regardless of ownership, more or less how I do using 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, something like MutationObserver (documentation here) . Changes because of other frameworks do not need to be captured.
asked by anonymous 05.07.2016 / 21:37

0 answers