Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- "use strict";
- class Model {
- constructor(mount, initial){
- this.modelContainer = new ObservableMap();
- this.subs = [];
- this.initial=initial;
- this.mount=mount;
- this.v = document.querySelector(mount).querySelectorAll('[data-bind]');
- Array.prototype.slice.call(this.v).forEach(el=>{
- if (el.type == "checkbox") {var val = 'checked';}else var val = 'value';
- el.addEventListener('input', ()=>{this.set(el.dataset['bind'], el[val])},false);
- if(el.type=='checkbox') el.addEventListener('change', ()=>{this.set(el.dataset['bind'], el[val])},false);
- this.subscribe((key,value)=>{
- if(el.dataset['bind']==key){
- el[val] = value;
- if (el.tagName == "SPAN" || el.tagName == "TEXT") { el.innerHTML = value }
- }
- });
- });
- Array.prototype.slice.call(this.v).forEach(el=>{
- if (el.type == "checkbox") {var val = 'checked';}else var val = 'value';
- this.modelContainer.listeners.forEach(s=>s(el.dataset['bind'], this.get(el.dataset['bind'])))});
- }
- subscribe(fn) {
- this.modelContainer.subscribe(fn);
- }
- toObject() {
- return this.initial;
- }
- set(key, value) {
- eval("this.initial."+key+"=value");
- this.modelContainer.set(key,value);
- console.log(this.modelContainer.get(key));
- }
- get(key) {
- return eval("this.initial."+key);
- }
- }
- class ObservableMap extends Map {
- constructor() {
- super();
- this.listeners = [];
- }
- subscribe( callback) {
- this.listeners.push(callback)
- return () => this.listeners = this.listeners.filter(c => c != callback);
- }
- set(key, value) {
- super.set(key, value)
- this.listeners.forEach(listener => listener(key, value))
- }
- get(key){
- return super.get(key);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement