The javascript model design For this design question. I implemented in three different ways below. They are all works.
My question is, which one is better? or why the one over the others? Or if you have better solution, please help me to better understanding the concept behind the question.
IFFE
/** method 1: IFFE */
const IFFEModel = (function() {
function ourModel(obj) {
this.oldModel = Object.assign({}, obj);
this.newModel = obj;
}
ourModel.prototype.set = function(key, value) {
this.oldModel = Object.assign({}, this.newModel);
this.newModel[key] = value;
this.on("change");
};
ourModel.prototype.get = function(key) {
console.log(this.newModel[key]);
return this.newModel[key];
};
ourModel.prototype.on = function(eventName, handler = () => {}) {
switch (eventName) {
case "change":
return handler(this.oldModel, this.newModel);
default:
return handler();
}
};
return ourModel;
})();
Revealing Prototype Pattern
/** method 2: Revealing Prototype Pattern */
const PrototypeModel = function(obj) {
this.oldModel = Object.assign({}, obj);
this.newModel = obj;
};
PrototypeModel.prototype = (function() {
const set = function(key, value) {
this.oldModel = Object.assign({}, this.newModel);
this.newModel[key] = value;
this.on("change");
};
const get = function(key) {
console.log(this.newModel[key]);
return this.newModel[key];
};
const on = function(eventName, handler = () => {}) {
switch (eventName) {
case "change":
return handler(this.oldModel, this.newModel);
default:
return handler();
}
};
return {
get: get,
set: set,
on: on
};
})();
ES6
/** method 3: ES6 */
class ECMAModel {
constructor(obj) {
this.oldModel = Object.assign({}, obj);
this.newModel = obj;
}
set(key, value) {
this.oldModel = Object.assign({}, this.newModel);
this.newModel[key] = value;
this.on("change");
}
get(key) {
console.log(this.newModel[key]);
return this.newModel[key];
}
on(eventName, handler = () => {}) {
switch (eventName) {
case "change":
return handler(this.oldModel, this.newModel);
default:
return handler();
}
}
}
/** test case */
let person = new PrototypeModel({ name: "john" });
person.get("name");
person.set("name", "johny");
person.get("name");
person.on("change", function(oldModel, newModel) {
console.log(oldModel, newModel);
});
And I notice that the way I create the custom event is little bit infeasible. Since I assuming that the callback function from the test has two elements, which might have a problem if considering scalability. Is there any other way to achieve that?
Aucun commentaire:
Enregistrer un commentaire