Skip to content
This repository has been archived by the owner on Nov 10, 2017. It is now read-only.

Commit

Permalink
Safer isolation of base store prototype.
Browse files Browse the repository at this point in the history
  • Loading branch information
n1k0 committed Feb 6, 2015
1 parent 588a130 commit b73ab10
Showing 1 changed file with 30 additions and 28 deletions.
58 changes: 30 additions & 28 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,35 @@
return baseActions;
};

var baseStoreProto = {
getState: function() {
return this.__state;
},
setState: function(state) {
if (typeof state !== "object") {
throw new Error("setState only accepts objects");
}
// Poor man's inefficient but strict & safe change check. I know.
var changed = Object.keys(state).some(function(prop) {
return !this.__state.hasOwnProperty(prop) ||
state[prop] !== this.__state[prop];
}, this);
if (!changed) return;
this.__state = merge({}, this.__state, state);
this.__listeners.forEach(function(listener) {
listener(this.__state);
}.bind(this));
},
subscribe: function(listener) {
this.__listeners.push(listener);
},
unsubscribe: function(listener) {
this.__listeners = this.__listeners.filter(function(registered) {
return registered !== listener;
});
}
};

DocBrown.createStore = function(storeProto) {
if (typeof storeProto !== "object") {
throw new Error("Invalid store prototype");
Expand All @@ -118,38 +147,11 @@
}, this);
}, this);
}

BaseStore.prototype = merge({
get state() {
return this.__state;
},
getState: function() {
return this.__state;
},
setState: function(state) {
if (typeof state !== "object") {
throw new Error("setState only accepts objects");
}
// Poor man's inefficient but strict & safe change check. I know.
var changed = Object.keys(state).some(function(prop) {
return !this.__state.hasOwnProperty(prop) ||
state[prop] !== this.__state[prop];
}, this);
if (!changed) return;
this.__state = merge({}, this.__state, state);
this.__listeners.forEach(function(listener) {
listener(this.__state);
}.bind(this));
},
subscribe: function(listener) {
this.__listeners.push(listener);
},
unsubscribe: function(listener) {
this.__listeners = this.__listeners.filter(function(registered) {
return registered !== listener;
});
}
}, storeProto);
}, baseStoreProto, storeProto);
return BaseStore;
};

Expand Down

0 comments on commit b73ab10

Please sign in to comment.