Sails.js 如何捕获链接集合通过自动订阅发布/订阅进行更新的事件?

Sails.js 如何捕获链接集合通过自动订阅发布/订阅进行更新的事件?,sails.js,waterline,Sails.js,Waterline,我在互联网上疯狂地搜索,这些帖子似乎与我最想做的事情有关: 但它们并没有起到很大的作用 我有 样板房 autosubscribe:['add:people','update:people'] attributes:{ people:{collection:'people',via:'room'}, temp:{type:'integer'} }, 模范人物 attributes: { name:{type:'string'}, room:{m

我在互联网上疯狂地搜索,这些帖子似乎与我最想做的事情有关:

但它们并没有起到很大的作用

我有 样板房

autosubscribe:['add:people','update:people']
attributes:{
     people:{collection:'people',via:'room'},
     temp:{type:'integer'}
},
模范人物

 attributes: {
      name:{type:'string'},
      room:{model:'rooms'},
      status:{type:'string',enum:['frustratedWithOfficialDocumentationBeingSoFracturedBetween:HiddenGitHubs_GoogleMisdirectsOnWebsite_OldYoutubes_ConceptsReferenceWhichAreForNoReasonSplitUp','personIsDead']
 },
publishParentUpdate:function(updatedObj,theThis,cb){
        //iterate over all the attributes that have a model key in the attributes of this model
        var error = null
        _.each(Z.getAssociationParents(theThis.identity), function(association) {
            var parentModel = sails.models[theThis.attributes[association].model]  //we can use this to directly address the parent model and do its finds / updates
            var embeddedUpdateObj = {} //container for the object that we are going to fake the update message with
            embeddedUpdateObj[theThis.identity]=updatedObj //set the updated properties inside the model
            try{ //probably don't need to try catch, but since we could make a mistake assuming some things above it seems smarter
                parentModel.publishUpdate(updatedObj[association],embeddedUpdateObj) //updating based on the id contained in our model and then packing in our happy object
            }catch(err){
                sails.log.warn('error while doing a collection update',err)
                error = err
            }
            cb(error)
        });
    },

    getAssociations: function(modelName) { //modelName is string!
        //function returns
        var assocArr = []
        if (sails.models[modelName]) {
            for (var a in sails.models[modelName].attributes) {
                if (sails.models[modelName].attributes[a].collection)
                    assocArr.push(a)
            }
        }
        return assocArr
    },

    //return the models that are your parents
    getAssociationParents: function(modelName) {
        var assocArr = []
        if (sails.models[modelName]) {
            for (var a in sails.models[modelName].attributes) {
                if (sails.models[modelName].attributes[a].model)
                    assocArr.push(a)
            }
        }
        return assocArr
    },
现在,让我们说,我发现我的一个人已经死亡,我需要简单地更新他们的状态,而不是在房间中添加另一个人(这可能会引发publishAdd事件)

People.findOne({name:'mrHappy'}).exec(err,mrHappyObj){
    mrHappyObj.status = 'personIsDead'
    mrHappyObj.save()  //etc
    People.publishUpdate(mrHappyObj.id,{status:mrHappyObj.status})
})
这对所有订阅“快乐先生”的人来说都很好,但如果我能找到一个东西,告诉他与之相关的房间他是自动死亡的,那就太棒了。我不在乎它是否只给我快乐先生的id,我真的很想自动得到通知

我尝试过但不需要阅读的额外内容。 我在我的人员模型中编写了这个函数,但它似乎非常笨拙

afterUpdate: function(updatedRecord, next)
 {
 sails.log.debug("I updated a People! derp",updatedRecord);
 sails.log.debug("key is ",sails.models[this.identity].primaryKey);
        var pKey = sails.models[this.identity].primaryKey
 var thisModelId = this.identity
        _.each(Z.getAssociationParents(this.identity), function(association) {
    // //so we now have the name of a parent model, we now have to find the id() of the parent that this
    // //NEW thing is pointing to?
    // //This is the parent that needs to be notified that he now owns a new vehicle. We have to take 
    // //the socket in his room and then use it to subscribe to this change!
//                 console.log("parent model found:",association)
                sails.log.debug("parent room",'sails_model_'+association+'s_'+ updatedRecord[association]+':'+'update')
                var sockets = sails.sockets.subscribers('sails_model_'+association+'s_'+ updatedRecord[association]+':'+'update')


                sails.log.debug("child room",'sails_model_'+thisModelId+'_'+ updatedRecord[pKey] +':'+'update')
                var deleteMeSocketsInChild = sails.sockets.subscribers('sails_model_'+thisModelId+'_'+ updatedRecord[pKey] +':'+'update')

                sails.log.debug("sockets in parent:", sockets, "child:",deleteMeSocketsInChild)

                for(var s in sockets)
                {
                    var sock = sails.io.sockets.socket(sockets[s]);

 //TODO !! send the subscribe method the needed primary key object
                    sails.models[thisModelId].subscribe(sock, Z.subscribePluralizer(pKey,updatedRecord[pKey])); //TODO - get the primary key as the last paramater to this function (updaterd record
 sails.log.debug("break")
    //   //could pass it a null


    // //If i am correct, updatedRecord is the whole record that has been updated. We are wanting to 
    // //subscribe the parent socket(s) to it. If this doesn't work , try using the information within
    // //the udpatedRecord to do the subscribe unless you can think of a better way.
 sails.log.debug("sockets in parent:", sockets, " NEW child:",deleteMeSocketsInChild)
                }

        });
 next()
 }
其他功能

 //return the models that are your parents
 getAssociationParents: function(modelName) {
 var assocArr = []
 if (sails.models[modelName]) {
 for (var a in sails.models[modelName].attributes) {
 if (sails.models[modelName].attributes[a].model)
 assocArr.push(a)
 }
 }
 return assocArr
 },


 //inspired by the pluralize function in \sails\lib\hooks\pubsub\index.js - we have to wrap our primary key up all pretty for it
 // since we don't expect our updatedRecords function to return an array of new objects (it shouldn't) we won't use the _.map function from pluralize
 subscribePluralizer: function(pKey, value) {
 //this function should be examined before using - 1-28-2015
 var newObj = {}
 newObj[pKey] = value
 newObj = [newObj]


 return newObj
 },

我愿意接受这里的建议。但这是一种享受

您可以将其放入您的模型中(或者理想地将其打包到服务或其他东西中)

然后这些为你服务的坏小子,我用Z.js来代替我的

 attributes: {
      name:{type:'string'},
      room:{model:'rooms'},
      status:{type:'string',enum:['frustratedWithOfficialDocumentationBeingSoFracturedBetween:HiddenGitHubs_GoogleMisdirectsOnWebsite_OldYoutubes_ConceptsReferenceWhichAreForNoReasonSplitUp','personIsDead']
 },
publishParentUpdate:function(updatedObj,theThis,cb){
        //iterate over all the attributes that have a model key in the attributes of this model
        var error = null
        _.each(Z.getAssociationParents(theThis.identity), function(association) {
            var parentModel = sails.models[theThis.attributes[association].model]  //we can use this to directly address the parent model and do its finds / updates
            var embeddedUpdateObj = {} //container for the object that we are going to fake the update message with
            embeddedUpdateObj[theThis.identity]=updatedObj //set the updated properties inside the model
            try{ //probably don't need to try catch, but since we could make a mistake assuming some things above it seems smarter
                parentModel.publishUpdate(updatedObj[association],embeddedUpdateObj) //updating based on the id contained in our model and then packing in our happy object
            }catch(err){
                sails.log.warn('error while doing a collection update',err)
                error = err
            }
            cb(error)
        });
    },

    getAssociations: function(modelName) { //modelName is string!
        //function returns
        var assocArr = []
        if (sails.models[modelName]) {
            for (var a in sails.models[modelName].attributes) {
                if (sails.models[modelName].attributes[a].collection)
                    assocArr.push(a)
            }
        }
        return assocArr
    },

    //return the models that are your parents
    getAssociationParents: function(modelName) {
        var assocArr = []
        if (sails.models[modelName]) {
            for (var a in sails.models[modelName].attributes) {
                if (sails.models[modelName].attributes[a].model)
                    assocArr.push(a)
            }
        }
        return assocArr
    },