How to load plugins already configured after page load by ajax

2

I have a page that has a form

In this way, it contains some inputs, which have classes, eg:

<input type="text" class="datepicker">
<input type="text" class="marcara-cpf">

And the configuration of some of the plugins is done in a js file

$(".datepicker").config...
$(".mascara-cpf").mask("000.000.000-00")

It turns out that when the page is loaded by ajax, it does not set the configuration of those plugins , having to call this configuration again. What makes the code repetitive, any place that has a cpf masraca, have to do this ... where I could only pass the% cos_de% mascara-cpf to the desired input.

I have read in some places that the implementation of class could solve (using require.js)

But I do not know how laborious it will be to implement this require.js in every app

Is there another elegant way to solve this problem with pages loading in ajax?

    
asked by anonymous 07.03.2015 / 15:24

1 answer

1

As pointed out by bfavaretto, Mutations Events , such as DOMNodeInserted were marked as obsolete, so browsers can stop supporting them.

On the other hand, we could use Mutations Observers , but only IE11 supports it, and we know how difficult it is to make the client understand that IE is a ... (Save Spartan!). >

So in this way, the best thing to do is to declare a function that loads these plugins, and to prevent the same plugin from running% of% times in a given element, it is important to always delimit a scope for this function.

Below is an example:

var content = $("#content");

var loadPlugins = function(escopo) {
  var maskCPF = $("[data-mask-cpf]", escopo);
  maskCPF.mask("999.999.999-99");
}

loadPlugins(document);
$(document).on("click", "#btAddMask", function () {
  $.post("Index/Home/0", {}, function(html) {
    var escopo = $(html);
    content.append(escopo);
      
    loadPlugins(escopo);
  }, "html");
});

//simular uma requisição AJAX via Post
$.post = function (url, data, sucess, dataType) {
  var row = $("<div>", { 
    "class": "row"
  });
  var maskCPF = $("<input>", { 
    "type": "text", 
    "data-mask-cpf": "" 
  });
  row.append(maskCPF);
  sucess(row[0].outerHTML);
}
body {

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="http://digitalbush.com/wp-content/uploads/2014/10/jquery.maskedinput.js"></script>
<button id="btAddMask">Incluir Campo</button>

<div id="content">
    <div class="row">
        <input data-mask-cpf="" />
    </div>
</div>
    
07.03.2015 / 18:44