javascript - Where do I need a closure for this one? -
i have constructor:
var editableitem = (function() { function editableitem(schema, item) { this.schema = _.clone(schema); this.item = _.clone(item); this.propertytypes = [ 'stringproperties', 'booleanproperties']; } editableitem.prototype = { createitem: function() { var self = this; self.propertytypes.foreach(function(type) { var properties = self.schema[type]; properties.foreach(function(property, i) { var itemproperty = self.item[type][property.id]; if (itemproperty) { properties[i].value = itemproperty; } }); }); self.schema.itemid = self.item._id; return self.schema; } }; return editableitem; })(); and each time use it, this...
async.parallel({ schema: function(callback) { schemas().findone({ _id: 'default' }, callback); }, items: function(callback) { items().find().toarray(callback); } }, function(err, result) { if (err) return callback(err); var = result.items.map(function(item) { return new editableitem(result.schema, item).createitem(); }); callback(null, all); }); ...i end array result last item repeated while others omitted.
my guess need add closure somewhere, , can see i've tried, still yields same result. ideas?
edit: i've found solution. it's not pretty, maybe here can explain why works , offer better solution...
in constructor, had: this.schema = _.clone(schema);
i changed to: this.schema = json.parse(json.stringify(schema));
this seems allocate new memory object, while _.clone still keeps references original object (i guess).
javascript numbers, strings & booleans equated , passed by value while objects , arrays equated , passed by reference. json representation of object string, equated , passed value.
if working json representation of schema gives different behaviour clone (an object), may conclude clone still contains references same objects original, uncloned schema; ie. clone not "deep".
as understand it, underscore.js doesn't yet offer deep clone lo_dash does. might try lo_dash's underscore compatibility build.
alternatively, stick json approach, doing same more formal deep clone method.
Comments
Post a Comment