Set Limit to Zero in Parse Counter

情到浓时终转凉″ 提交于 2019-12-25 18:52:54

问题


I'm trying to set my counter in parse to not go below zero when the score is being decremented, at the moment it can go to negative numbers. How can I set the minimum limit to be zero?

This is what I've managed to do so far:

btnPointTeamD.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                object.increment("team_d_score");
                                object.saveInBackground();
                            }
                        });

btnMinusTeamC.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                object.increment("team_c_score", -1);
                                object.saveInBackground();
                            }
                        });

回答1:


Cloud code has what's called beforeSave and afterSave triggers. beforeSave is what you need here.

A beforeSave trigger contains all of the new data (note: none of the old) and you can check object.dirty("key"); to see if that field has changed. You also don't have to do any checks for this specific case.

Parse.Cloud.beforeSave("ClassName", function(request, response) {
    var object = request.params.object;
    if( object.get("team_c_score") < 0 ) object.set("team_c_score", 0);
    response.success();
});

Some notes: If you return response.error(), the save will note go through, so this is how you validate input. A field contains illegal characters, or data you didn't expect? Throw an error so it doesn't get saved.

You also shouldn't put anything in the success response. That will cause an error.

This function gets called automatically if it exists, and will always be called. You can't skip it. Even if you update data from the dashboard, this gets called. Same with afterSave triggers, although modifying an object in those will not do anything unless you save it.

This should go in your main.js, or a file required by main.js. I have a folder for each of my custom classes. Each class has a classNameController.js, which contains the beforeSave, afterSave, initializer, and any cloud code functions relating directly to that object.

Main requires each of these controllers, which opens up all of the Parse.Cloud endpoints to the server.

beforeSave and afterSave triggers on hosted Parse.com had a 3 second timeout. I am not aware if there is a timeout for parse-server. I've never tested it. But don't have more than a couple server calls to be safe.



来源:https://stackoverflow.com/questions/44817822/set-limit-to-zero-in-parse-counter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!