2012-01-17 3 views
1

API를 사용하여 데이터베이스에 저장하는 모델이 있습니다. 내 문제는이 모델을 업데이트 할 때입니다. 처음으로 무엇인가를 변경하고 model.save를 호출하면 속성이 JSON으로 전달되어 API를 파싱하고 문제없이 저장합니다. 이제 같은 뷰에서 두 번째로 해당 모델을 변경하면 model.save가 정의되지 않은 객체를 내 모델에 추가합니다. API는이 객체를보고 PUT 요청을 거부합니다.Backbone.js RESTful API 관련 문제

왜 두 번째 업데이트가 아닌 첫 번째 업데이트에서 작동합니까?

도와 주셔서 감사합니다.

여기 코드는 이해할 수 있기를 바랍니다. model.save에 모든 인수를 전달

var LDAccount = Backbone.Model.extend({ 
    defaults : { 
     ACC_NUM : '', 
     BOOK_DATE : '', 
     F_NAME : '' 
    }, 
    template : _.template(
     "<p>Full Name</p><input data-id='F_NAME' type=text value='<%= F_NAME %>' />" + 
     "<p>Book Date</p><input data-id='BOOK_DATE' type=text value='<%= BOOK_DATE %>' />" 
    ), 
    urlRoot : 'api/account' 
}); 

var LDAccountView = Backbone.View.extend({ 
    el : '', // set this when instantiating this model in the router 
    initialize : function(options) { 
     this.model = options.model; 
     this.model.id = options.id; 
     this.model.bind('change', this.render, this); 
     this.model.bind('error', this.renderError, this); 
    }, 
    render : function() { 
     $(this.el).html(this.model.template(this.model.toJSON())); 
     $(this.el).append(
      '<div id="model_buttons" >' + 
      '<input type=button id=reset value=Reset />' + 
      '<input type=button id=save value=Save />' + 
      '</div>' 
     ); 
     return this; 
    }, 
    events : { 
     'click #save' : 'save2db' 
    }, 
    save2db : function() { 
     var $fields = $(this.el).find('input[type=text]'); 
     var modObj = new Object(); 
     $fields.each(function() { 
      var $field = $(this); 
      var prop = $field.attr('data-id'); 
      var val = $field.val(); 
      modObj[prop] = val; 
     }); 
     this.model.set(modObj); 
     console.log(modObj); 
     this.model.save({ 
      success : function() { 
       self.reset(); 
      } 
     }); 
     return false; 
    }, 
    renderError : function() { 
     $(this.el).append('<p class=error>Account does not exist</p>'); 
    }, 
    reset : function() { 
    } 
}); 

var MainView = Backbone.View.extend({ 
    // code omitted since it's not relevant to the question 
}); 

var LDRouter = Backbone.Router.extend({ 
    routes : { 
     "account/:modl/:acc_num": "renderView" 
    }, 

    initialize : function() { 
     this.search = new MainView({ el : '#main'}); 
    }, 

    // THIS IS THE VIEW THAT RENDERS THE MODEL 
    renderView : function(modl, acc_num) { 
     var self = this; 
     var model = null; 

     switch(modl) { 
      case 'account': 
       model = new LDAccount(); 
       break; 
      // these other models were omitted for clarity 
      case 'asset': 
       model = new LDAsset(); 
       break; 
      case 'info': 
       model = new LDInfo(); 
       break; 
      default: 
       model = new LDAccount(); 
       break; 
     } 

     this.account = new LDAccountView({ id : acc_num, el : '#accDetail', model : model }); 
     this.account.reset = function() { 
      self.renderView(modl,acc_num); 
     }; 
     this.account.model.fetch(); 
    }, 

    accountInfo : function (acc_num) { 
     var root = ''; 
     var url = window.location.href; 
     var hashPos = url.indexOf('#'); 
     if(hashPos != -1) { 
      root = url.substr(0,hashPos); 
     } else { 
      root = url; 
     } 
     window.location = root + "#account/account/" + acc_num; 
    } 

}); 

$(function() { 
    var app = new LDRouter(); 
    Backbone.history.start(); 
}); 
+0

실제로 수행하는 작업에 대한 추가 정보를 제공하는 몇 가지 예제 코드를 추가하면 실제로 도움이됩니다. – ryanmarc

+0

모델 코드 및 저장 방법을 추가하십시오. –

답변

1

음, 가 작동하는 것 같다.

this.model.save(
    { 
     success: function() { 
      // do some stuff here 
     }, 
     error: function() { 
      // do other stuff here 
     } 
    } 
); 

다른 세계에서 , 나는 가지고 있던 문제를 해결했다. 왜 나는 save가 모델 속성에 추가 된 정의되지 않은 객체를 전달하는지 궁금해합니다.

+3

여전히 api가 말한대로 작동 할까? 첫 번째 매개 변수는 모델에서 변경할 속성의 해시이고 두 번째 매개 변수는 콜백입니다. 그래서'.save ({}, {success : function})'는 예상 한대로해야합니다. http://documentcloud.github.com/backbone/#Model-save –

+0

Andreas가 맞습니다. 첫 번째 매개 변수는 this.model.set ('someProperty', 'someValue') 코드를 대체 할 수 있습니다. OP와 같이 모델 속성을 이미 설정 한 경우 Andreas가 위에 표시된 것처럼 빈 개체를 전달할 수 있습니다. –

0

POST 데이터 부분을 저장하는 변수를 ''와 같이 초기화하는 것을 잊었 기 때문입니다. 따라서 변수에 문자열로 데이터가 추가되면 'undefined'에 추가됩니다. 해결 : 문제는 서버에 있습니다!