문제

기본적으로 Node 서버에 GET 요청을 보내려고 노력하여 블로그 게시물을 가져와 링크를 만들 수 있습니다. 나는한다 collection.fetch, 성공적인 GET 요청 (오른쪽 객체를 보내는 노드 서버 로그)을 완료합니다. 이 모델은 올바른 데이터를 성공적으로 구문 분석하지만 컬렉션을 사용하려고 할 때 비어 있다고합니다. 코드는 다음과 같습니다.

var mdm = mdm || {};

// MODEL
mdm.Post = Backbone.Model.extend({
        parse: function( response ) {
        response.id = response._id;
        console.log(response); // logs the two documents
        return response;
    }
});

// COLLECTION
mdm.Posts = Backbone.Collection.extend({
    model: mdm.Post,
    url: '/api/posts'
});

// MODEL VIEW
mdm.LinkView = Backbone.View.extend({
    template: _.template( $('#link_template').html() ),

    render: function() {
        this.$el.html( this.template( this.model.toJSON() ));
        return this;
    }
});

// COLLECTION VIEW
mdm.LinksView = Backbone.View.extend({
    el: '#link_list',

    initialize: function() {
        this.collection = new mdm.Posts();
        this.collection.fetch({reset: true});
                // makes the request properly, but collection is empty
        this.render();
                // never gets called because the collection is empty
        console.log(this.collection.length); 
                // logs a length of 0
    },

    render: function() {
        // renders collection
    }
});

$(function() {
    new mdm.LinksView();
});

데이터가 전송되고 모델에서 구문 분석되므로 컬렉션이 비어있는 것이 확실하지 않습니다. 모든 도움은 대단히 감사하겠습니다.

도움이 되었습니까?

해결책

당신이 당신의 견해에서 모델을 보지 못하는 가장 큰 이유는 렌더가 비동기 전에 일어나기 전에 발생하기 때문입니다. fetch 완료되었습니다.

아래와 같은 것은 더 잘 작동합니다.

mdm.LinksView = Backbone.View.extend({
    el: '#link_list',

initialize: function() {
    this.collection = new mdm.Posts();
    this.listenTo(this.collection, 'reset', this.render);
    this.collection.fetch({reset: true});
}

위의 코드는 청취자를 설정합니다 reset 이벤트 collection 그리고 render 그런 일이 발생하면 기능합니다.

또한 지나갈 수 있습니다 success 그리고 error 핸들러가 fetch 렌더링 기능을 수동으로 호출하십시오.

this.collection.fetch({
    success: _.bind(function() { 
        this.render(); }, this)
});

도움이 되었기를 바랍니다!

다른 팁

@fbynite의 의견에 따라 문제는 fetch 비동기식. 컬렉션 뷰를 다음과 같은 변경했는데 트릭을 수행했습니다.

initialize: function() {
    var self = this;
    this.collection = new mdm.Posts();
    this.collection.fetch({reset: true,
        success: function() {
            self.render();
            console.log(self.collection.length);
        }
    });
},

이 코드는 백본 자습서에서 수정 된 것이므로 다른 사용자도 비슷한 문제가 발생할 수 있습니다. http://addyosmani.github.io/backbone-fundamentals/#exercise-2-book-library---your-first-restful-backbone.js-app

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top