2012-02-20 2 views
2

그래서 기존 항목을 편집 할 때 괜찮은지 확인할 수 있습니다. 그러나, 내가 만들고 싶다면, 어떤 이유로 든 유효성 검사가 시작되지 않습니다. 대신 아래 오류를보고 있습니다.백본 - 유효성 검사가 생성시 작동하지 않고 업데이트/편집 만 가능합니까?

//this is if the field I want to validate is empty 
Uncaught TypeError: Object #<Object> has no method 'get' 

//this is if everything in the form is filled out 
Uncaught TypeError: Cannot call method 'trigger' of undefined 

여기 내 (ja)의 상대적인 부분이 있습니다. 미안의 경우 과부하, 내가 많이 나는 가능한 한 구체적으로 할 수있는 추가하고 싶었 :

Comic = Backbone.Model.extend({ 
    initialize: function() { 
     this.bind("error", this.notifyCollectionError); 
     this.bind("change", this.notifyCollectionChange); 
    }, 
    idAttribute: "ComicID", 
    url: function() { 
     return this.isNew() ? "/comics/create" : "/comics/edit/" + this.get("ComicID"); 
    }, 
    validate: function (atts) { 
     if ("Name" in atts & !atts.Name) { 
      return "Name is required"; 
     } 
     if ("Publisher" in atts & !atts.Publisher) { 
      return "Publisher is required"; 
     } 
    }, 
    notifyCollectionError: function (model, error) { 
     this.collection.trigger("itemError", error); 
    }, 
    notifyCollectionChange: function() { 
     this.collection.trigger("itemChanged", this); 
    } 
}); 
Comics = Backbone.Collection.extend({ 
    model: Comic, 
    url: "/comics/comics" 
}); 
comics = new Comics(); 

FormView = Backbone.View.extend({ 
    initialize: function() { 
     _.bindAll(this, "render"); 
     this.template = $("#comicsFormTemplate"); 
    }, 
    events: { 
     "change input": "updateModel", 
     "submit #comicsForm": "save" 
    }, 
    save: function() { 
     this.model.save(
      this.model.attributes, 
      { 
       success: function (model, response) { 
        model.collection.trigger("itemSaved", model); 
       }, 
       error: function (model, response) { 
        model.trigger("itemError", "There was a problem saving " + model.get("Name")); 
       } 
      } 
     ); 

     return false; 
    }, 
    updateModel: function (evt) { 
     var field = $(evt.currentTarget); 
     var data = {}; 
     var key = field.attr('ID'); 
     var val = field.val(); 
     data[key] = val; 
     if (!this.model.set(data)) { 
      //reset the form field 
      field.val(this.model.get(key)); 
     } 
    }, 
    render: function() { 
     var html = this.template.tmpl(this.model.toJSON()); 
     $(this.el).html(html); 
     $(".datepicker").datepicker(); 
     return this; 
    } 
}); 

NotifierView = Backbone.View.extend({ 
    initialize: function() { 
     this.template = $("#notifierTemplate"); 
     this.className = "success"; 
     this.message = "Success"; 
     _.bindAll(this, "render", "notifySave", "notifyError"); 
     comics.bind("itemSaved", this.notifySave); 
     comics.bind("itemError", this.notifyError); 
    }, 
    events: { 
     "click": "goAway" 
    }, 
    goAway: function() { 
     $(this.el).delay(0).fadeOut(); 
    }, 
    notifySave: function (model) { 
     this.message = model.get("Name") + " saved"; 
     this.render(); 
    }, 
    notifyError: function (message) { 

     this.message = message; 
     this.className = "error"; 
     this.render(); 
    }, 
    render: function() { 
     var html = this.template.tmpl({ message: this.message, className: this.className }); 
     $(this.el).html(html); 
     return this; 
    } 
}); 

var ComicsAdmin = Backbone.Router.extend({ 

    initialize: function() { 
     listView = new ListView({ collection: comics, el: "#comic-list" }); 
     formView = new FormView({ el: "#comic-form" }); 
     notifierView = new NotifierView({el: "#notifications" }); 
    }, 
    routes: { 
     "": "index", 
     "edit/:id": "edit", 
     "create": "create" 
    }, 
    index: function() { 
     listView.render(); 
    }, 
    edit: function (id) { 
     listView.render(); 
     $(notifierView.el).empty(); 
     $(formView.el).empty(); 
     var model = comics.get(id); 
     formView.model = model; 
     formView.render(); 
    }, 
    create: function() { 
     var model = new Comic(); 
     listView.render(); 
     $(notifierView.el).empty(); 
     $(formView.el).empty(); 
     formView.model = model; 
     formView.render(); 

    } 
}); 

jQuery(function() { 
    comics.fetch({ 

     success: function() { 
      window.app = new ComicsAdmin(); 
      Backbone.history.start(); 
     }, 
     error: function() { 

     } 
    }); 
}) 

그래서, 야해 내도 검증 받고있을 만들? 왜 그게 아니야?

+0

어떤 백본 버전을 사용하고 있습니까? – ryanmarc

+0

동일한 문제가 발생했습니다. '새로운 모델 ({foo : bar})'을 할 때 검증이 실행됩니다. 모델은 당신이 사용하고있는 어떤 모델 검증을 통해서도'foo'를 결코 통과하지 않을 것입니다. – tkone

+0

그래서 우리는 0.5.3에서 0.9.1로 업그레이드했고 0.9.1은 0.5.3에서 사용 된 것과 동일한 모델을 사용합니다. 초기화는 모델 유효성 검사를 호출하지 않습니다. 정말 저에게 벙어리 감각이 있습니다 - 어디서나 사용하지 않을 것이라면 유효성 검사를 수행해야한다는 요점은 무엇입니까? – tkone

답변

2

확인. 그래서 저는 여기서 약간의 성공을 거두고 있습니다.

먼저, 내 자신의 유효성 검사 프레임 워크, Backbone.Validator을 작성했습니다. 왜냐하면 내가 발견 한 것들 중 하나가 마음에 들지 않았기 때문입니다.

두 번째로 new Model 생성 중에 제공된 개체에 silent: false을 설정하여 유효성 검사 루틴을 설정하는 유효성 검사 프레임 워크를 얻을 수 있습니다.

내 유효성 검사 프레임 워크의 use_defaults 매개 변수를 사용하는 것과 동시에 초기 테스트에서 설정하는 동안 잘못된 데이터를 무시할 수 있습니다. 나는 아직도 이것에 대한 더 많은 테스트를하고 있지만 Chrome 브라우저 콘솔에서 OK가 될 것으로 보인다.

+0

그리고 모든 좋은 것들과 마찬가지로, 이것은 더 이상 작동하지 않는 것 같습니다 ... 아니면 그것은 결코 없었고 잘못된 결과를 가지고 그것에 대해서 생각하게되어 너무 흥분했습니다 ... – tkone

4

모델의 새 인스턴스를 만들 때 validate 메서드가 호출되지 않습니다. 백본 documentation에 따르면 유효성 검사는 set 또는 save 전에 만 호출됩니다. 그 속성은 (question 9709968 참조)

  • 더 우아한 방법은 유효성 검사를 호출 한 다음 설정

    • 당신은 새로운 모델을 만들 수 있고 :

      나는이 문제에 어려움을 겪고 발견 솔루션 관련 질문에 있어요 백본 documentation에 설명 된 같은 모델의 새로운 인스턴스를 생성하기 때문에 방법 모델을 초기화 할 때 (question 7923074 참조)

    나는이 솔루션을 완벽하게 만족하지 않다 오류가 발생했을 때 발생하지 않아야합니다. 불행히도 두 가지 솔루션 모두에서 모델의 새로운 인스턴스가 계속 붙어 있습니다.

    편집 : 모델의 새로운 인스턴스로 붙어 실제로는 꽤 좋습니다. 이렇게하면 사용자가 유효성 검사기를 통과하지 못한 이유에 대한 사용자 의견을 제공하고 입력 내용을 수정할 수있는 기회를 제공 할 수 있습니다.

  • 관련 문제