【问题标题】:How to call function every time collection updates from server?每次从服务器更新集合时如何调用函数?
【发布时间】:2016-01-14 23:49:15
【问题描述】:

例如,在 this 控制器中,当另一个用户更改 Paries 集合时,控制器方对象会自动更新,但我们如何捕获此更新并运行一些控制器逻辑?

this.helpers({ parties: () => Parties.find({}) });

具体问题: 收到的答案并不能解决我的问题,因为它不是我需要在更新时执行的服务器逻辑或任何数据库操作。实际上,我需要运行的是控制器逻辑。

在以下示例中,如果表单未更改,我将禁用提交按钮。 isFormChange 函数将派对与 originalParty 进行比较。当派对从服务器端更改时,我需要重新定义 originalParty 值。那么我该怎么做呢?

<form ng-submit="vm.updateParty()">
  <input type="text" ng-model="vm.party.name">
  <input type="submit" ng-disabled="!vm.isFormChanged()" value="Submit">
</form>

指令控制器:

function Ctrl($scope, $reactive) {
  let vm = this;
  $reactive(vm).attach($scope);

  vm.helpers({ party: () => Parties.findOne({_id: vm.partyId}) });
  let originalParty = angular.copy(vm.party);
  vm.isFormChanged = isFormChanged;
  vm.updateParty = updateParty;

  function isFormChanged() {
    return !angular.equals(vm.party, originalParty);
  }

  function updateParty() {
    Meteor.call('updateParty', vm.party._id, vm.party.name);
  }
}

【问题讨论】:

    标签: meteor angular-meteor


    【解决方案1】:

    使用collection-hooks 包在更新、更新、插入和删除之前或之后运行代码。

    myCollection.after.update(userId, doc, fieldNames, modifier, options){
      ...your code
    }
    

    【讨论】:

    • 感谢您的回答,但请检查指定问题。
    【解决方案2】:

    如果您在Meteor methods 中有您的数据库功能,您可以在服务器上运行您的逻辑。

    例子:

    Parties = new Mongo.Collection("parties");
    
    if (Meteor.isClient) {
        // This code only runs on the client
        Meteor.subscribe("parties");
        /* a helper or event can run the Meteor.call() */
        var partyData = {}; // get partyData
        Meteor.call("insertParty", partyData,
            // callback function
            function (error, result) {
                if (error) { console.log(error); };
            });
    }
    
    if (Meteor.isServer) {
        // This code only runs on the server
        Meteor.publish("parties", function () {
            return Parties.find({});
        });
        Meteor.methods({
            insertParty: function (partyData) {
                // insert logic to run on partyData here
                Parties.insert(partyData);
            }
        })
    }
    

    【讨论】:

    • 感谢您的回答,但请检查指定问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    相关资源
    最近更新 更多