I have an object that is used as a hash table to store key value pairs in javascript:
Storage["key"] = "value".
I've fo开发者_Python百科und we can use defineSetter to have setters for each key, however, we need to know all key names beforehand. Is there a way of doing something whenever a value is set this way?
So for example, when doing:
Storage["key"] = "value";
I want it to be handled by a custom method like:
customMethod : function(aKey, aValue) {
//do something with these two params
// inform somebody else about this.
}
Thoughts/Suggestions?
No, there isn't currently a way to catch all property assignments. Firefox 4 introduced an experimental JavaScript Proxy API which would allow you to do this (have a proxy forward all calls to an inner object but also trigger some additional action when properties are set) but it would probably be an overkill here - even if this API were stable and implemented in other browsers.
You can override __defineSetter__
of the object to gain finer control. Caveat: Won't work in all browsers!
See this post for more details: John Resig: JavaScript Getters and Setters
精彩评论