带有 Backbone.js 的投票系统 [英] Voting system with Backbone.js

查看:15
本文介绍了带有 Backbone.js 的投票系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有 upVotes 属性的 Book 模型.Book 实例可以从数据库(MongoDB)中查询、修改、保存.如果用户为一本书点赞,我会更新 upVotes 计数,并将整个模型保存回服务器.

I have a Book model that has the property upVotes. Book instances can be queried from the database (MongoDB), modified, and then saved. If a user upvotes a book, I update the upVotes count, and save the whole model back to the server.

问题是,如果在加载实例的时间和保存实例的时间之间有其他人投票,那么这两票将被保存为一票.我需要的是一种简单的方法来表达将模型增加 1 个服务器端",而不是将模型增加 1 个客户端并希望不会发生冲突".

The problem is that if someone else votes between the time the instance is loaded, and the time the instance is saved, then the two votes will be saved as just one vote. What I need is an easy way to say "increment the model by 1 server-side", instead of "increment the model by 1 client-side and hope there will be no conflict".

推荐答案

你不必为了改变一件事而将整个模型保存到服务器,你可以(在这种情况下应该)添加一个 upVote 方法对您的模型执行递增投票"AJAX 调用到您的服务器.在你的模型中,你会有这样的东西:

You don't have to save the whole model to the server just to change one thing, you can (and should in this case) add an upVote method to your model that does an "increment upvotes" AJAX call to your server. In your model you'd have something like this:

upVote: function() {
    var self = this;
    $.ajax({
        url: '/some/upvote/path',
        type: 'POST',
        success: function(data) {
            self.set('upVotes', data.upVotes);
        },
        // ...
    });
}

然后视图将使用它来处理 upvote 操作:

And then the view would have this to handle the upvote action:

upVote: function() {
    // Highlight the upvote button or provide some other feedback that
    // the upvote has been seen.
    this.model.upVote();
}

并且您可能在模型的 upVotes 属性上有一个用于更改事件的侦听器,以正确增加显示的投票计数器(如果您有这样的东西).

and you'd probably have a listener for change events on the model's upVotes property to properly increment the displayed upvote counter (if you have such a thing).

此外,您在服务器上的 /some/upvote/path 只会发送一个 $inc update 到 MongoDB 中,以避免在您的服务器上出现相同的同时发生两件事"的问题.如果您使用的是关系型数据库,您最终会希望执行类似 update t set upvotes = upvotes + 1 where id = ?.

Furthermore, your /some/upvote/path on the server would just send an $inc update into MongoDB to avoid the same "two things happening at once" problem on your server. If you were using a relational database, you'd want to end up doing something like update t set upvotes = upvotes + 1 where id = ?.

不需要在客户端或服务器上进行查询、更新、保存"来回进行简单的增量操作.相反,将增量视为单个增量操作,并将该增量一直推送到最终的持久数据存储层.

There is no need for a "query, update, save" round trip on either the client or the server for a simple increment operation. Instead, treat the increment as a single increment operation and push that increment all the way down to your final persistent data storage layer.

这篇关于带有 Backbone.js 的投票系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆