2

所以我试图从我的模型中获取验证以实际禁用保存按钮,但在包含新输入时重新验证。任何人都知道尝试此操作的最佳方法。谢谢!我的方法遇到的问题是,一旦它被禁用,它就不会返回状态。

这是 main.js 文件

(function () {
    window.App = {
        Models: {},
        Collections: {},
        Views: {},
        Templates: {},
        Router: {}

    };

    // MODEL
    App.Models.User = Backbone.Model.extend({
        defaults: {
            firstName: 'first',
            lastName: 'last',
            email: 'Email',
            phone: '222',
            birthday: '07/22/1980'
       },

        validate: function (attrs) {

            if (!attrs.firstName) {
                return 'You must enter a real first name.';
            }
            if (!attrs.lastName) {
                return 'You must enter a real last name.';
            }
            if (attrs.email.length < 5) {
                return 'You must enter a real email.';
            }
            if (attrs.phone.toString().length < 10 ) {
                //&& attrs.phone === int
               return 'You must enter a real phone number, if you did please remove the dash and spaces.';
            }
           // if (attrs.birthday.length < 2) {
             //   return 'You must enter a real city.';
            //}
        },

        initialize: function() {
             this.on('invalid', function (model, invalid) {
                console.log(invalid);
                alert(invalid);
            });
        }

    });

    //var userModel = new App.Models.User();

    //VIEW
    App.Views.User = Backbone.View.extend({
        el: '#user',
        //model: userModel,
        //tagName: 'div',
        //id: 'user',
        //className: 'userProfile',
        //template: _.template($("#userTemplate").html()),
        //editTemplate: _.template($("#userEditTemplate").html()),


        initialize: function (){

        },

        render: function() {
            this.template = Handlebars.compile($("#userTemplate").html());
            this.editTemplate = Handlebars.compile($("#userEditTemplate").html());

            this.$el.html(this.template(this.model.toJSON()));
            return this;
        },

        events: {
            'click button.edit': 'editProfile',
            'click input.save': 'saveEdits',
            'click button.cancel': 'cancelEdits'
        },

        editProfile: function () {
            this.$el.html(this.editTemplate(this.model.toJSON()));

        }, 

        saveEdits: function () {
            var form = $(this.el).find('form#updateUser');
            this.model.set({

                firstName : form.find('.firstName').val(),
                lastName : form.find('.lastName').val(),
                email: form.find('.email').val(),
                phone: form.find('.phone').val(),
                birthday: form.find('.birthday').val()

            }, {validate: true} );

        if(!this.model.isValid()) {
            console.log('run');
            $('.save').attr("disabled", "disabled");

        } else {
            console.log('run2');
            alert('Changes have been made.');
            $('.save').removeAttr("disabled");
            return this.render();
        }


    },


        },

        cancelEdits: function() {
            this.render();
        }

    });
    //start history service
    Backbone.history.start();

    var user = new App.Views.User({model: new App.Models.User()});
    user.render();
})();

这是玉文件:

extends layout
block content   
    div.centerContent

        h4 User goes here with equal before it no space
            div#user
                p #{firstName} #{lastName}
                p #{email}
                p #{phone}
                p #{birthday}
                button.edit Edit

        script(id="userTemplate", type ="text/template")
                p {{firstName}} {{lastName}} 1
                p {{email}} 2 
                p {{phone}} 3 
                p {{birthday}} 4
                button.edit Edit

        script(id="userEditTemplate", type ="text/template")
            div
                form(action="#")#updateUser
                    input(type="text", class="firstName", value='{{firstName}}') 
                    input(type="text", class="lastName", value='{{lastName}}')
                    input(type="email", class="email", value='{{email}}')
                    input(type="number", class="phone",, value='{{phone}}')
                    input(type="date", class="birthday", value='{{birthday}}')
                input(type="submit", value="Save").save Save
                button.cancel Cancel
        hr
        script(type="text/javascript", src="/js/main.js")
4

1 回答 1

6

这里的问题是您正在调用方法的{ validate: true }选项model.set,然后您随后调用model.isValid().

当您model.setvalidate选项设置为 true 的情况下调用时,Backbone.js 不会设置您传递的属性,除非它们都通过验证。因此,在您调用model.isValid()该模型时,该模型已更改回以前的版本(.set调用之前)。model.isValid()自动调用该model.validate()方法并将模型的当前属性传递给它。

validate在您的示例中,该方法传递给的值是模型isValid的当前(有效)属性。正因为如此,isValid()总是要验证为真。这将导致您永远无法达到您的else条款。

这里的解决方案不是调用isValid来查看您的模型是否有效(在传递validate: trueset方法之后)检查model.validationError. 如果model.validationError是一个真实值,那么你知道你的模型是无效的。

这是一个JSFiddle,其中包含如何执行此操作的示例,以及一些文档。

于 2013-07-12T03:28:58.783 回答