簡體   English   中英

修改骨干.js中的視圖元素時,模型不會改變

[英]Model doesn't change when modify view elements in backbone.js

我正在驗證模型的屬性(名稱),以確保客戶必須在注冊表中輸入其名稱。

查看:

define(["jquery" ,
 "underscore" ,
 "backbone" ,
 "text!templates/CustomerTemplate.html",
 "models/Customer"
],function($ , _ , Backbone, CustomerTemplate, CustomerModel){
 var CustomerView = Backbone.View.extend({
    initialize : function(){
        this.listenTo(this.model, 'change', this.render);
    },
    events : {
        'submit #customerForm' : 'Customer'
    },
    Customer : function(e){
        e.preventDefault()
        var _customer = new CustomerModel({
            UID: "00000000-0000-0000-0000-000000000000",
            Sex: 0,
            Name: $("#name").val(),
        });
        this.model.save(_customer,{validate: true},{
                wait:true,
                success:function(model, response) {
                    console.log('Successfully saved!');
                },
                error: function(model, error) {
                    console.log(model.toJSON());
                    console.log('error.responseText');
                }
        });
    },
    render : function(){
        var customertemplate = _.template(CustomerTemplate);
        this.$el.html(customertemplate(this.model.toJSON()));
        return this;
    }
 });
 return CustomerView;
});

模型:

define(["underscore" , "backbone"],function(_ , Backbone){
 var CustomerModel = Backbone.Model.extend({
    urlRoot: "myurl",
    initialize : function(){
        this.bind('invalid', function(model, error) {
            console.log(error);
        });
    },
    validate: function (attrs){
        if ( !attrs.Name) {
            return 'You must provide a name';
        }
    },
    defaults : {
        UID: "00000000-0000-0000-0000-000000000000",
        Sex: 0,
        Name: "",
    }
 });
 return CustomerModel;
});

問題:即使屬性Name不為nullvalidate方法中的錯誤消息仍然會出現( You must provide a name )。

任何想法可能導致此的表示贊賞。 謝謝。

當您在CustomerView中調用this.model.save時,將為其傳遞在上一條語句中實例化的新Customer模型。 這不是您想要的; 您要么要調用_customer.save()來保存全新模型,要么(更可能是)您希望將新屬性傳遞給現有模型,並保存該模型:

var newAttrs = {
        UID: "00000000-0000-0000-0000-000000000000",
        Sex: 0,
        Name: $("#name").val(),
    };
this.model.save(newAttrs); 

當您在現有代碼中調用this.model.save(_customer, {validate: true})時,該Customer模型將傳遞給validate()函數。 而且該模型沒有Name屬性。 確實具有Name屬性-您可以通過_customer.get('Name') -但您應遵循Backbone約定,並假定您的validate方法正在獲取“簡單” JavaScript對象,而不是Backbone模型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM