Hi,
A brief OT before the actual question, you can make your each call
more efficient. Instead of:
objectToArray(json.element).each(function(ele){ ... }.bind
(this));
use each's second param, 'context':
objectToArray(json.element).each(function(ele){ ... }, this);
Enumerable#each will use the given context to call the iterator.
Okay, to the actual question:
I'm with Richard, this is a design flaw in the backend. Even if
returning just one element, it should return a one element array.
> So my question is, it is possible doing that by adding the each
> () method to the Object class,
> and making it do something like objectToArray(this) before
> iterating over the this object?
You'd have to add it to Object.prototype, and you Really Really Really
do not want to add things to Object.prototype. A huge number of
scripts (including Prototype) would break. You _could_ add a new
method to Object that uses an object's each method if it has one or
assumes it's just one element otherwise (since Array and Hash both
have each):
// Completely untested
Object.each = function(obj, iterator, context) {
if (Object.isFunction(obj.each)) {
return obj.each.call(context, iterator);
}
iterator.call(context, obj);
return obj;
}
...and then use it:
Object.each(function(ele){ ... }, this);
...but I'd say if you can't fix the backend, then explicitly using
something like objectToArray where this may come up seems like your
best option.
FWIW,
--
T.J. Crowder
tj / crowder software / com
Independent Software Engineer, consulting services available
On May 29, 8:57 am, dgalvez <[email protected]> wrote:
> the point is, sometimes i receive a json object like
>
> var json = {
> element: ['1','2','3']
> }
>
> and sometimes element has just one element so it is presented as
> a String not an Array:
> var json = {
> element: '1'
> }
>
> And i want to iterate over json.element independently of its
> type, i normally do something like:
>
> objectToArray(json.element).each(function(ele){ ... }.bind
> (this));
>
> where objectToArray is something like this:
>
> function objectToArray(obj) {
> if (!Object.isArray(obj) && !Object.isHash(obj)) {
> var objArray = [obj];
> return objArray;
> }
> return obj;
> }
> So my question is, it is possible doing that by adding the each
> () method to the Object class,
> and making it do something like objectToArray(this) before
> iterating over the this object?
>
> Sorry if i haven´t explained well.
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Prototype & script.aculo.us" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/prototype-scriptaculous?hl=en
-~----------~----~----~----~------~----~------~--~---