Created
May 6, 2014 05:39
-
-
Save mrzafod/b6212dc564b1382e7ddb to your computer and use it in GitHub Desktop.
Meteor.js local collection change hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Layers = App.Collection('layers'); | |
Layers.find().observeChanges({ | |
'added': function (id, fields) { | |
var doc = this.results._map[id]; | |
// now we could access and modify the doc | |
// --------------------------------------------------------------------- | |
// here I wanna know a type of the layer and then fill some default | |
// properties for doc | |
if(fields.type && fields.type == 'text') | |
doc.addedText = "original has text"; | |
if(fields.type && fields.type == 'image') | |
doc.addedImage = "original has image"; | |
if(fields.type && fields.type == 'svg') | |
doc.addedSvg = "original has svg"; | |
}, | |
'changed': function (id, fields) { | |
var doc = this.results._map[id]; | |
// now we could access and modify the doc | |
// --------------------------------------------------------------------- | |
// here I wanna know and store increment of "x". | |
// Lets calculate "delta" as "fields.x" minus "doc.lastx" and write the value | |
// in "delta" field | |
if(fields.x) { | |
var delta = fields.x - doc.lastx || fields.x; | |
doc.delta = delta; | |
doc.lastx = doc.lastx || fields.x; | |
} | |
} | |
}); | |
// test added | |
// --------------------------------------------------------------------- | |
Layers._collection.insert({'_id': '00000000000', type: 'text'}); | |
Layers._collection.insert({'_id': '00000000001', type: 'image'}); | |
Layers._collection.insert({'_id': '00000000002', type: 'svg'}); | |
console.log(Layers.find({}, {reactive: false}).fetch()); | |
// test added | |
// --------------------------------------------------------------------- | |
Layers._collection.remove({}); | |
Layers._collection.insert({'_id': '00000000000'}); | |
Layers._collection.update('00000000000', {$set: {'x': 500}}); | |
Layers._collection.update('00000000000', {$inc: {'x': Math.random() * 10}}, function () { | |
console.log(Layers.findOne('00000000000')) | |
Layers._collection.update('00000000000', {$set: {'x': Math.random() * 100}}, function () { | |
console.log(Layers.findOne('00000000000')) | |
Layers._collection.update('00000000000', {$inc: {'x': Math.random() * 1000}}, function () { | |
console.log(Layers.findOne('00000000000')) | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment