2014-12-14 4 views
0

저는 StackOverflow와 나머지 interwebz를 해결하여이 문제에 대한 해결책을 찾기 위해 노력했습니다. 나는 백본을 배우고 있으며 이것을 깰 수없는 것처럼 보입니다. RESTful CRUD 작업에서 완벽하게 작동합니다. 컬렉션이 업데이트 될 때 (예 : 누군가 레코드를 데이터베이스에 추가하기위한 POST 요청을 수행하는 경우) 페이지에서 아무 것도 변경되지 않습니다.컬렉션의 모델을 저장하거나 삭제할 때 백본보기가 업데이트되지 않습니다.

ModelSave 성공 콜백에서 Backbone의 문서에 따르면 모델을 저장하는 컬렉션이 자동으로 업데이트되므로 명시 적으로 선언 할 필요가 없습니다. 추가/수정/삭제할 때 왜 표시된 페이지에서 변경되지 않는 이유는 무엇입니까? GAH! 여기에 코드가 있습니다. 표준 JSON 배열과

<html> 
    <head> 
     <title>Test</title> 
    </head> 
    <body> 
    <script type="text/template" id="search_template"> 
     <label>Search</label> 
     <input type="text" id="search_input" /> 
     <input type="text" id="number" /> 
     <input type="button" id="search_button" value="Add" /> 
     <input type="button" id="edit_button" value="Edit" /> 
     <input type="button" id="delete_button" value="Delete" /> 
    </script> 
    <script type="text/template" id="row_template"> 
     <tr> 
      <td><%= id %></td> 
      <td><%= name %></td> 
      <td><%= job %></td> 
     </tr> 
    </script> 
    <div id="view"> 

    </div> 
    <table id="rows"> 
     <thead> 
      <tr> 
       <td>ID</td> 
       <td>Name</td> 
       <td>Jobs</td> 
      </tr> 
     </thead> 
     <tbody id="lmao"> 

     </tbody> 
    </table> 
    <script src="https://code.jquery.com/jquery-latest.min.js"></script> 
    <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script> 
    <script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script> 
    <script> 

     var lel = Backbone.Model.extend({ urlRoot: 'lol.php' }); 
     //var x = new lel; 
     //var lee = Backbone.Mode.extend(); 

     var rows = Backbone.Collection.extend({ model: lel, url: 'lol.php' }); 

     dice = Backbone.View.extend({ 
      initialize: function(){ 
       this.render(); 
      }, 
      render: function(a){ 
       this.$el.html($('#search_template').html()); 
      }, 
      events: { 
       'click input[value="Add"]': 'hay', 
       'click #search_input': 'gaz', 
       'click #edit_button': 'edit', 
       'click #delete_button': 'del' 
      }, 
      gaz: function(){ $('#search_input').val('') }, 
      hay: function(){ 
       var self = this; 
       var x = new lel; 
       x.save({ name: $('#search_input').val(), id: null }); 
      }, 
      edit: function(){ 
       var x = new lel; 
       x.save({ name: $('#search_input').val(), id: $('#number').val() }, { success: function(r){ alert(r.toJSON()); } }); 
      }, 
      del: function(){ 
       var x = new lel({ id: $('#number').val() }); 
       x.destroy({ success: function(r){ console.log(r.toJSON()); } }); 
      } 
     }); 

     var lmf = Backbone.View.extend({ 
      initialize: function(){ 
       _.bindAll(this, "render"); 
       this.collection = new rows(); 
       this.collection.on("change:all", function(){ alert('changed'); }, this); 
       this.collection.fetch({ success: this.render }); 
       console.log(this.collection); 
       console.log(this.model); 
      }, 
      render: function(){ 
       var self = this; 
       _.each(this.collection.models, function(item){ 
        //console.log('row '+item); 
        var dict = item.toJSON(); 
        var template = _.template($('#row_template').html()) 
        var html = template(dict); 
        self.$el.append(html); 
       }); 
      }, 
      addAll: function(){ 
       var self = this; 
       self.$el.append('fafa'); 
       //this.$el.html(this.model.get('id')); 
      } 
     }); 

     //this.$el.html(self.collection.length); 
     var throz = new dice({ el: $('#view') }); 
     var v = new lmf({ el: $('#lmao') }); 

    </script> 
    </body> 
</html> 

서버가 응답 (.fetch()가 호출 될 때) :

[{"id":"60","name":"r","job":""},{"id":"55","name":"r","job":""},{"id":"54","name":"s","job":""},{"id":"53","name":"r","job":""},{"id":"56","name":"ee","job":""},{"id":"57","name":"r","job":""},{"id":"58","name":"ffff","job":""},{"id":"59","name":"rrrrrr","job":""}] 

도와주세요! 이것은 너무 초조하다!

+0

콜렉션의 유일한 이벤트 바인딩은'this.collection.on ("change : all", ...)'이며'all' 속성이 변경되기를 기다리고 있습니다. 다른 이벤트 (http://backbonejs.org/#Events-catalog)를 청취해야합니다. 그리고 'listenTo'로 전환하고 오래된 'var self = this' (요즘은 항상 더 좋은 방법이 있습니다)를 제거하십시오. –

답변

0

의견을 언급 한 내용의 @mu is too short을 확장하면 내 생각에 collection에서 올바른 이벤트를 듣지 못하고 있습니다. 해고당한 add 또는 remove 이벤트를 청취해야합니다. 즉, 청취자를 설정하십시오.

this.listen to(this.collection, "add", this.render); 
this.listen to(this.collection, "add", this.render); 

보기에서. 당신은 model의 변화를 감지 할 경우에 childView 당신은 renderchildView을에

다음
this.listen to(this.model, "change", this.render); 

필요, 즉 model 변경을 기다리는 리스너를 설정해야합니다 model은 전체 컬렉션과 연관되지 않으며 관련이 없습니다. 변경하려는 특정 속성을 찾고있는 경우 "change:attr"을 수신하십시오. 여기서 attr은 수신하려는 속성의 이름입니다.

+0

감사! 이게 내 문제를 해결했습니다! – Tejas

관련 문제