表决系统与Backbone.js的 [英] Voting system with Backbone.js

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

问题描述

我有了财产 upVotes A 图书模式。 图书实例可以从数据库(MongoDB的)进行查询,修改,然后保存。如果用户upvotes一本书,我更新 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".

推荐答案

您不必保存整个模型到服务器只是为了改变一件事,你可以(也应该在这种情况下)添加一个给予好评法模型,它是增量upvotesAJAX调用到您的服务器。在你的模型你有这样的事情:

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);
        },
        // ...
    });
}

和则认为会有这种处理给予好评的行动:

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).

此外,你的 /一些/给予好评/路径服务器将只发送的 $ INC 更新到MongoDB中,以避免同样的两件事情在服务器上发生一次的问题。如果你使用的是关系型数据库,你要结束了做这样的事情更新t将upvotes = upvotes + 1其中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天全站免登陆