Skip to content

Instantly share code, notes, and snippets.

@mwiemarc
Created December 1, 2016 14:04
Show Gist options
  • Save mwiemarc/16c4d95c406ae9a96b13253827f04fcb to your computer and use it in GitHub Desktop.
Save mwiemarc/16c4d95c406ae9a96b13253827f04fcb to your computer and use it in GitHub Desktop.
Simples MVVM Example with Javascript
<!--
English:
This example show how do a simple MVVM code with html+js
You can change the data in design and the object person will be changed, you can too make the change by the console(js) of the property from the object and the visual will be changed.
Portugues:
Esse exemplo mostra como fazer um simples MVVM framework com HTML e JS
Você pode alterar os dados visualmente e o objeto pessoa vai ser alterado e também se você fizer a alteração via console da propriedade o visual será modificado.
-->
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.min.js" type="text/javascript"></script>
<script src="mvvm.js" type="text/javascript"></script>
<script src="main.js" type="text/javascript"></script>
</head>
<body>
<input id="Nome" name="Nome" type="text" placeholder="Nome" data-bind="Nome" />
<input id="Idade" name="Idade" type="number" placeholder="Idade" data-bind="Idade"/>
<script type="text/javascript">
</script>
</body>
</html>
(function($){
$(function(){
function Pessoa() {
this._nome = "";
this._idade = "";
};
}
var pessoa = new Pessoa();
mvvm.observe(pessoa);
})(jQuery);
function CriadorDeGetAndSetter(obj) {
var captalize = function() { return this.replace( /(^|\s)([a-z])/g , function(m, p1, p2) { return p1 + p2.toUpperCase(); }); };
for (var prop in obj) {
if ($.isFunction(obj[prop]))
continue;
(function (privatename, proto) {
var propname = captalize.call(privatename.replace("_", ""));
Object.defineProperty(proto, propname, {
get: function () {
return obj[privatename];
},
set: function (value) {
obj[privatename] = value;
obj["PropertyChanged"](propname);
}
});
})(prop, obj);
}
obj["PropertyChanged"] = function (name) {
alert(name);
};
}
var mvvm = {
observe: function (obj) {
CriadorDeGetAndSetter(pessoa);
$('[data-bind]').each(function (index, item) {
var dataBindField = $(item).attr("data-bind");
$(item).change(function () {
var functionsToBeCalled = [];
for(var v in obj){
if(v.indexOf("__") != -1 && $.isFunction(obj[v]))
functionsToBeCalled.push(v);
}
obj[dataBindField] = $(this).val();
for(var i = 0; i < functionsToBeCalled.lenght; i++){
obj[functionsToBeCalled[v]].call(obj);
}
});
obj["PropertyChanged"] = function (nome) {
$('[data-bind=' + nome + ']').val(obj[nome]);
};
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment