Backbone.js的Ajax调用 [英] backbone.js ajax calls

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

问题描述

我是Backbone.js的学习一个新的应用我建立。
我需要执行一个AJAX调用( REST服务)来验证。

在哪里是该呼叫的正确​​的地方吗?在模型,视图或别的地方?具体涉及到Backbone.js的MVC模式。

 < HTML和GT;
< HEAD>
<脚本SRC =LIB / jQuery的-1.6.1.min.js>< / SCRIPT>
&所述; SCRIPT SRC =LIB / json2.js>&下; /脚本>
<脚本SRC =LIB /下划线-min.js>< / SCRIPT>
<脚本SRC =LIB /骨干-min.js>< / SCRIPT>< SCRIPT LANGUAGE =JavaScript的>
      $(函数(){
         VAR LoginView = Backbone.View.extend({
          EL:$(#登录表格」),          事件:{
            点击#login:登录
          },          登录:函数(){
              警报(你好);
           }
        });        window.LoginView =新LoginView();
      });
    < / SCRIPT>
  < /头>
  <身体GT;
    <形式的行动=/登录ID =登录形式>
      用户名:其中;输入类型=文本ID =用户名>< BR>
      密码:LT;输入类型=密码ID =密码>< BR>
      <按钮ID =登录>登录和LT; /按钮>
    < /表及GT;
  < /身体GT;
< / HTML>


解决方案

创建一个身份验证模型,存储后的状态(用户名,密码,还记得我),以及响应状态(登录失败,登录接受)..

  App.Model.authentication = Backbone.Model.extend({
    默认值:{
        用户名: ,
        密码:
        与rememberMe:假的,
        LoginFailed:假的,
        LoginAccepted:假的
    },
    网址:API /认证
});

更新视图使用该模型:

  $(函数(){
    VAR LoginView = Backbone.View.extend({
        型号:新App.Model.authentication()
        EL:$(#登录表格」),
        事件:{
            点击#login:登录
        },        登录:函数(){
            this.model.save({用户名:此$ el.find(#用户名),
                密码:此$ el.find(#密码)},{
                成功:函数(){
                    / *现在更新视图* /
                },
                错误:函数(){
                    / *在这里处理错误code * /
                }
            });
        }
    });
}

);

调用Model.Save()将发出一个POST请求到服务器,虽然在服务器上的这种情况下你没有实际保存任何东西,但检查凭证和发回的对象具有相同的模式,但与LoginAccepted字段设置适当。

不实现自定义JQuery的AJAX的文章 - 它不是在骨干网的精神,处理它都为你通过它的REST接口引擎盖下

REST接口和各种REST操作的更多细节和URL的骨干网使用此处的 HTTP://$c$cbyexample.info/2012/04/30/backbone-in-baby-steps-part-3/

在AJAX一件事VS model.save()的争论。如果你的应用是一个无状态的聊天室如IRC - 自定义AJAX调用它发送消息给其他用户在聊天室,但不集中保存的消息......你会扔掉所有的骨干REST功能和重新实现它们因为你没有实际'节能',你真的只是'发送'。这将花费你大量的工作来重新实现功能,已经存在的,因为语义而已。请务必阅读model.save()作为model.post() - 它不只是救了 - 它发送

I 'm learning Backbone.js for a new app I'm building. I need to perform an AJAX call(REST SERVICE) to authenticate.

Where is the correct place for this call? In the Model, View or somewhere else? specifically related to Backbone.js MVC model.

<html>
<head>
<script src="lib/jquery-1.6.1.min.js"></script>
<script src="lib/json2.js"></script>
<script src="lib/underscore-min.js"></script>
<script src="lib/backbone-min.js"></script>   

<script language="javascript">
      $(function(){
         var LoginView = Backbone.View.extend({
          el: $("#login-form"),

          events: {
            "click #login": "login"
          },

          login: function(){
              alert("Hello");
           }
        });

        window.LoginView = new LoginView();
      });
    </script>   
  </head>
  <body>
    <form action="/login" id="login-form">
      Username: <input type="text" id="username"><br>
      Password: <input type="password" id="password"><br>
      <button id="login">Login</button>
    </form>
  </body>
</html>

解决方案

Create an authentication Model, that stores the post state (username, password, remember me) as well as the response state (login failed, login accepted)...

App.Model.authentication= Backbone.Model.extend({
    defaults: {
        Username: "",
        Password: "",
        RememberMe: false,
        LoginFailed: false,
        LoginAccepted: false
    },
    url:"api/authentication"
});

Update the View to use the model:

   $(function () {
    var LoginView = Backbone.View.extend({
        model: new App.Model.authentication(),
        el: $("#login-form"),
        events: {
            "click #login": "login"
        },

        login: function () {
            this.model.save({username: this.$el.find("#username"),
                password: this.$el.find("#password")}, {
                success: function () {
                    /* update the view now */
                },
                error: function () {
                    /* handle the error code here */
                }
            });
        }
    });
}

);

Calling Model.Save() will issue a post request to the server, although in this instance on the server you're not actually saving anything, but check the credentials and sending back an object with the same model, but with the "LoginAccepted" field set appropriately.

Don't implement custom JQuery AJAX Posts - Its not in the spirit of backbone, which handles it all for you under the hood via its REST interface.

More details on the REST interface and the various REST Actions and URLS that backbone uses here: http://codebyexample.info/2012/04/30/backbone-in-baby-steps-part-3/

One more thing on the AJAX vs model.save() debate. If your application was a stateless chat room like IRC - which sends messages to other users in the chat room but doesn't save the messages centrally... would you throw away all of backbone's REST functionality and re-implement them with custom AJAX calls because you're not ACTUALLY 'saving', you're really just 'sending'. That would cost you a huge amount of work to re-implement functionality that's already there, just because of semantics. Always read model.save() as model.post() - its not just for saving - its for sending.

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

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