Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add initial getters and setters support

  • Loading branch information...
commit 501d772551ba0658d8ea26c2cb9b821c52cfc855 1 parent 408043f
@twpayne authored
Showing with 55 additions and 3 deletions.
  1. +32 −3 src/mvc/mvcobject.js
  2. +23 −0 src/mvc/mvcobject_test.js
View
35 src/mvc/mvcobject.js
@@ -38,6 +38,15 @@ goog.inherits(mvc.MVCObject, goog.events.EventTarget);
/**
+ * @param {string} s String.
+ * @return {string} Capitalized string.
+ */
+mvc.MVCObject.capitalize = function(s) {
+ return s[0].toUpperCase() + s.slice(1);
+};
+
+
+/**
* @private
* @type {Object.<string, function(*)>}
*/
@@ -73,7 +82,7 @@ mvc.MVCObject.prototype.bindTo =
var eventType = targetKey + '_changed';
var noNotify = goog.isDef(opt_noNotify) ? opt_noNotify : false;
this.listeners_[key] = goog.events.listen(target, eventType, function() {
- goog.object.set(this, key, target.get(targetKey));
+ this.setInternal_(key, target.get(targetKey));
if (!noNotify) {
this.notify(key);
}
@@ -86,7 +95,12 @@ mvc.MVCObject.prototype.bindTo =
* @return {*} Value.
*/
mvc.MVCObject.prototype.get = function(key) {
- return goog.object.get(this, key);
+ var getterName = 'get' + mvc.MVCObject.capitalize(key);
+ if (goog.object.containsKey(this, getterName)) {
+ return this[getterName]();
+ } else {
+ return goog.object.get(this, key);
+ }
};
@@ -112,13 +126,28 @@ mvc.MVCObject.prototype.set = function(key, value) {
goog.object.containsKey(this.setters_, key)) {
this.setters_[key](value);
} else {
- goog.object.set(this, key, value);
+ this.setInternal_(key, value);
this.notify(key);
}
};
/**
+ * @private
+ * @param {string} key Key.
+ * @param {*} value Value.
+ */
+mvc.MVCObject.prototype.setInternal_ = function(key, value) {
+ var setterName = 'set' + mvc.MVCObject.capitalize(key);
+ if (goog.object.containsKey(this, setterName)) {
+ this[setterName](value);
+ } else {
+ goog.object.set(this, key, value);
+ }
+};
+
+
+/**
* @param {Object.<string, *>} values Values.
*/
mvc.MVCObject.prototype.setValues = function(values) {
View
23 src/mvc/mvcobject_test.js
@@ -348,3 +348,26 @@ function testPriorityUndefined() {
assertUndefined(a.get('k'));
assertUndefined(b.get('k'));
}
+
+
+function testSetter() {
+ var a = new mvc.MVCObject();
+ var x;
+ a.setX = function(value) {
+ x = value;
+ };
+ a.set('x', 1);
+ assertEquals(1, x);
+}
+
+
+function testGetter() {
+ var a = new mvc.MVCObject();
+ var getterCalled;
+ a.getX = function() {
+ getterCalled = true;
+ return 1;
+ };
+ assertEquals(1, a.get('x'));
+ assertTrue(getterCalled);
+}
Please sign in to comment.
Something went wrong with that request. Please try again.