骨干JS型号节省超过一次 [英] Backbone js Model Save more than once

查看:200
本文介绍了骨干JS型号节省超过一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

荫学习骨干JS,所以我已经开始创建示例应用程序。

Iam learning Backbone js and so I have started creating sample application.

BTW,IAM面临的一个问题,现在即,模型是在我的数据库中保存不止一次。我的意思是,当你点击创建用户,你会看到一个表格,所以当我点击创建用户按钮,细节越来越保存不止一次在我的数据库等所有重复的用户信息显示在主页上。

BTW, iam facing one problem now ie., model is saving more than once in my database. I mean when you click 'Create User' , you'll see a form, so when I click that 'Create User' button, details are getting saved more than once in my DB and so all duplicate users info displayed in the home page.

事实上的IAM努力实践这个视频: https://www.youtube.com/watch?v=FZSjvWtUxYk

Actually iam trying to practice this video: https://www.youtube.com/watch?v=FZSjvWtUxYk

输出应该是这样的: http://backbonetutorials.com/videos/beginner/#/new

这是我的code:

<html>
<head>
<link rel="stylesheet"
    href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.1/css/bootstrap.min.css">
<script type="text/javascript">
    /*$.getJSON('api/users/1',function(data){

        console.log(data);
    });*/
</script>


</head>

<body>

    <div class="container">
        <h1> User Manager</h1>
        <hr/>       
        <div class="page"></div>
    </div>

    <script type="text/template" id="user-list-template">
        <a href="#/new" class="btn btn-primary">New User</a>
        <hr/>
        <table class="table stripped">
            <thead>
                <tr>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Age</th>
                </tr>
            </thead>
            <tbody>
                <% _.each(users, function(user){  %>
                <tr>
                    <td><%= user.get('firstName') %></td>
                    <td><%= user.get('lastName') %></td>
                    <td><%= user.get('age') %></td>
                </tr>
                <% }); %>                       
            </tbody>
        </table>
    </script>

    <script type="text/template" id="add-user-template">
        <legend>Create User</legend>
        <form class="add-user-form">
            First Name <input type="text" id="firstName"/><br/>
            Last Name <input type="text" id="lastName"/><br/>
            Age <input type="text" id="age"/><hr/>
            <input type="submit" value="Create User">
        </form>
    </script>


<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>

<script type="text/javascript">

    var UsersList = Backbone.Collection.extend({
        url: 'api/users'
    });

    var User = Backbone.Model.extend({
        urlRoot: 'api/users'
    });

    var UsersListView = Backbone.View.extend({
        el: '.page',
        render: function(){
                var that = this;
                var users = new UsersList();
                users.fetch({
                    success: function(usersList){
                    var template = _.template($('#user-list-template').html())({users: usersList.models});
                    that.$el.html(template);
                }
            });         
        }
    });

    var AddUserView = Backbone.View.extend({
        el: '.page',
        render: function(){
            var template = _.template($('#add-user-template').html())({user:null});
            this.$el.html(template);
        },
        events: {
            'submit .add-user-form': 'saveOrUpdateUser' 
        },
        saveOrUpdateUser: function(e){
            e.preventDefault();
            var userDetails = {firstName: $('#firstName').val(), lastName: $('#lastName').val(), age: $('#age').val()};
            var user = new User();
            user.save(userDetails,{ //SEEMS LIKE HERE HAVING SOME PROBLEM
                success: function(){
                    console.log('INSIDE SUCCESS..');
                    router.navigate('',{trigger: 'true'});
                }
            });             
        }
    });

    var Router = Backbone.Router.extend({
        routes:{
            '':'home',
            'new':'addUser'
        }       
    });

    var router = new Router();
    router.on('route:home',function(){
        var usersListView = new UsersListView();
        usersListView.render();
    });
    router.on('route:addUser',function(){
        var addUserView = new AddUserView();
        addUserView.render();
    });


    Backbone.history.start();

</script>

</body>

</html>

请建议我出了什么问题,如何解决这一问题?

Please suggest me what went wrong and how to fix this?

推荐答案

@MarciaYudkin你会发现,当你第一次加载你的网站,并创建一个用户,该用户第一次不保存副本。但是,下一次你填写一个 CREATEUSER 的形式,用户将得到保存两次。这里发生的事情是,你是从次僵尸患! (啊!)

@MarciaYudkin you'll notice that when you first load your site and create a user, that first user does not save a duplicate. However, the next time you fill out a CreateUser form, the user will get saved twice. What's happening here is that you are suffering from Zombie Views! (Ahh!)

一个僵尸View是,你以为走了一个观点,但实际上仍然在后台运行。由于他们还活着,他们也仍难免其观点事件。您在code检测到的僵尸的看法是:

A Zombie View is a view that you thought went away, but in fact remains in the background. Since they're still alive, they are also still bound its view events. The zombie view you detected in your code is:

router.on('route:addUser',function(){
    var addUserView = new AddUserView(); // <---Right here!
    addUserView.render();
});

每一个用户遵循路由时间:ADDUSER 路线,他们最终创造了新的 AddUserView 。这种观点使自身和自身附加到DOM。你可能会认为,既然你删除你从DOM旧观点,这将完全消失,对吧?那么,它的确实的---从DOM ---而不是从内存!由于这一观点仍然事件绑定到DOM,它没有得到垃圾收集。当被绑定到任何previous意见的DOM元素被触发(如通过点击它),电流,以及所有的老,未予处置,意见仍然绑定到它,并且他们都触发响应。这是发生了什么给你。在这里,看到这个小提琴我熟了。

Every time a user follows the route:addUser route they end up creating a new AddUserView. This view renders itself and attaches itself to the DOM. You would think that since you "removed" your old view from the DOM, it would simply disappear, right? Well, it does---from the DOM---but not from memory! Since that view still has event bound to the DOM, it does not get garbage collection. When a DOM element that was bound to any previous views is triggered (like by clicking it), the current, as well as all the old, undisposed, views are still bound to it, and all of them respond to the trigger. That's what's happening to you. Here, see this fiddle I cooked up.

出这个问题的方法是让周围的视图的引用,这样你可以妥善处置。因此,例如,你可以在你的路由器连接到视图的引用,并做

The way out of this is to keep a reference to the view around, so that you could properly dispose of it. So, for example, you could attach a reference to the view in your router, and do,

router.on('route:addUser',function(){
   // If the view exists, remove it
   if (router.addUserView) {
     router.addUserView.remove();
     router.addUserView.off();
  }
  router.addUserView = new AddUserView();
  router.addUserView.render();
});

下面我们调用Backbone.View.remove(),这确实这一点。$ el.remove()的scences,有效地消除被提及的DOM元素背后我们的观点和释放绑定事件。现在,我们的观点可以被垃圾收集!

Here we call Backbone.View.remove(), which really does this.$el.remove() behind the scences, effectively removing the DOM elements referred to by our view and releasing the bound events. Now our view can be garbage collected!

您可以看到我最近怎么回答了这个问题查找有关此另一个角度:用户数据保存不止一次的。而且我觉得我会失职,如果我不包括德里克·贝利对僵尸的看法开创性的文章(从那里我得到了我的大部分信息),<一个href=\"http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/\"相对=nofollow>僵尸!跑! (管理页面过渡骨干企业应用套件)

You can see how I answered this question recently for another angle on this: Saving User Data more than once. And I think I'd be remiss if I didn't include Derick Bailey's seminal article on zombie views (from where I got most of my information), Zombies! RUN! (Managing Page Transitions In Backbone Apps)

这篇关于骨干JS型号节省超过一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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