2013-01-10 3 views
1

백본에 익숙하지 않아 서버에서 Json 형식으로 데이터를 보내고 받으려고합니다. 그냥 작동하지 않습니다. 여기에 (BTW, 내가 백본 분위기를 사용하고 있습니다) 내 코드입니다 :백본 컬렉션 가져 오기 실행 안 함

컬렉션

define(['sandbox', '../models/message'], function(sandbox, Message) { 
'use strict'; 

var Messages = sandbox.mvc.Collection({ 
    model: Message, 
    url: '/messagelist.php', 
    localStorage: new sandbox.data.Store('messages-backbone-require'), 
    parse: function(response){ 
     return response.rows; 
    } 
}); 

return Messages; 

}); 

모델

define(['sandbox'], function(sandbox) { 
'use strict'; 

var Message = sandbox.mvc.Model({ 

    defaults: { 
     opened: '', 
     messageid: '', 
     phonenumber: '', 
     numbername: '', 
     text: '' 
    }, 
    parse: function(data){ 
     return data; 
    } 

}); 

return Message; 
}); 

보기

define(['sandbox', '../models/message', 'text!../templates/incoming_messages.html'], function(sandbox, Message, incomingMessagesTemplate) { 
'use strict'; 

var AppView = sandbox.mvc.View({ 
    widgetTemplate: sandbox.template.parse(incomingMessagesTemplate), 

    events: { 
     'click .refresh': 'refresh' 
    }, 

    initialize: function() { 
     this.$el.html(this.widgetTemplate); 
     sandbox.events.bindAll(this); 
     this.collection.bind('createMessageList', this.createMessageList); 
    }, 

    createMessageList: function() { 
     // Will work with the received data here 
    }, 

    render: function() { 
     var handle = 'h4'; 
     this.$el.draggable({handle: handle}); 
     this.createMessageList(); 
    }, 

    refresh: function() { 
     this.createMessageList(); 
    } 


}); 

return AppView; 

}); 

홈페이지

define(['sandbox', './views/app', './collections/messages'], function(sandbox, AppView, Messages) { 
'use strict'; 

return function(options) { 
    var messages = new Messages(); 

    new AppView({ 
     el: sandbox.dom.find(options.element), 
     collection: messages 
    }).render(); 

    messages.fetch({ 
     data: { 
      type: 'incoming', 
      offset: 0, 
      offsetcount: 25 
     }, 
     type: 'GET', 
     success: function() { 
      console.log(messages.models); // Shows an empty array. 
     } 
    }); 
}; 
}); 

로그를 검사했는데 ajax 요청 (collection.fetch())이 실행 중이 아니거나 서버와 통신 할 수없는 것으로 보입니다. 이 문제를 어떻게 해결할 수 있습니까?

답변

2

문제는 Backbone.LocalStorage 플러그인에 있습니다. Collection.localStorage을 지정하면 플러그인이 fetch 명령을 대신 처리하고 서버가 아닌 로컬 저장소에서 데이터를 읽습니다.

이 문제를 해결하는 방법에 대한 일부 옵션은 내 answer in this SO question을 참조하십시오.

+0

로컬 저장소 플러그인이 실제로 '가져 오기'보다는 '백본 동기화'를 대신 사용합니까? 그러나 그것은 단지 니트 따기 일뿐입니다. –

+0

@muistooshort, yessir, OP의 질문은 'fetch'가 아니라는 것입니다. 'sync'가 어떻게 작동하는지 알지 못하면 원인을 설명하는 가장 간단한 방법은 일부 모서리를 자르는 것입니다. 'sync' 오버라이드에 대한 핵심은 링크 된 답변에서 설명합니다. – jevakallio