문제

백본에서 첫 번째 애플리케이션을 수행하고 있는데 이벤트를 첨부하려고 하면 이상한 일이 발생합니다.

지금까지 이 코드를 얻었습니다.

//View for @girl, EDIT action
GirlEditView = Backbone.View.extend({
    initialize: function(el, attr) {
        this.variables = attr;
        console.log(attr);
        this.render();
    },
    render: function() {
        var template = _.template( $("#girl_edit").html(), this.variables );
        $(this.el).html( template );
        $("#edit_girl").modal('show');
    }
});

//View for @girl
GirlView = Backbone.View.extend({
    initialize: function(el, attr) {
        this.variables = attr;
        this.render();
    },
    render: function() {
        var template = _.template( $("#girl_template").html(), this.variables );
        $(this.el).html( $(this.el).html() + template );
    },
    events: {
        "click p.modify": "modify"
    },
    modify: function() {
        //calls to modify view
        new GirlEditView({el : $("#edit_girl")}, this.variables);
    }
});


//One girl from the list
Girl = Backbone.Model.extend({
    initialize: function() {
        this.view = new GirlView({el : $("#content")}, this.attributes );
    }
});

//all the girls
Girls = Backbone.Collection.extend({
    model: Girl,
});




//do magic!
$(document).ready(function() {

    //Underscore template modification
    _.templateSettings = {
        escape : /\{\[([\s\S]+?)\]\}/g,
        evaluate : /\{\[([\s\S]+?)\]\}/g,
        interpolate : /\{\{([\s\S]+?)\}\}/g
    }

    //get initial data and fill the index
    var list = [];
    $.getJSON('girls.json', function(data) {
        list = [];
        $.each(data, function(key, val) {
            list.push( new Girl(val) );
        });

        var myGirls = new Girls(list);
        console.log( myGirls.models);
    });
});

보시다시피.

저는 컬렉션을 사용하여 모든 소녀를 저장하고 있으며 데이터는 Ruby의 REST API에서 제공됩니다.

각 소녀는 새로운 모델 인스턴스를 생성하고 그 안에 뷰 인스턴스를 연결했습니다.

그것이 좋은 습관인지는 모르겠지만 더 나은 방법을 생각할 수 없습니다.

각 뷰는 고유한 ID를 가진 콘텐츠를 만듭니다.소녀-1 소녀-2 그리고 계속하세요.

이제 템플릿에 편집 버튼이 있습니다.내 원래 아이디어는 onclick 이벤트를 공격하고 편집 보기를 트리거하여 렌더링하는 것입니다.

예상대로 작동하고 있습니다.

지금까지의 문제는 다음과 같습니다.

이벤트가 트리거되면 렌더링된 뷰를 "소유"하는 컬렉션이 아닌 모든 컬렉션(소녀)이 편집 뷰를 실행합니다.

내 질문은 내가 뭘 잘못하고 있는 걸까요?

정말 감사합니다

도움이 되었습니까?

해결책

모든 GirlView가 동일한 뷰를 사용하기 때문에 모든 편집 뷰가 나타납니다. el:

this.view = new GirlView({el : $("#content")}, this.attributes );

그런 다음 더 많은 HTML을 추가하도록 렌더링합니다.

render: function() {
    var template = _.template( $("#girl_template").html(), this.variables );
    $(this.el).html( $(this.el).html() + template );
}

백본 이벤트는 다음을 사용하여 바인딩됩니다. delegate 보기에 el.따라서 여러 뷰가 동일한 것을 공유하는 경우 el, 여러 개가 있을 거예요 delegate동일한 DOM 요소에 첨부되어 이벤트가 내분으로 엉망이 될 것입니다.

약간 거꾸로 된 내용이 있습니다.모델은 뷰를 소유하지 않으며, 뷰는 모델과 컬렉션을 관찰하고 해당 이벤트에 응답합니다.당신은 이것을 보게 될 것입니다 문서에 바로:

생성자 / 초기화 new View([options])

[...] 전달되면 뷰에 직접 첨부되는 몇 가지 특수 옵션이 있습니다. model, collection, [...]

일반적으로 컬렉션을 생성하면 c, 그리고 해당 컬렉션을 전달하여 뷰를 생성합니다.

var v = new View({ collection: c })

또는 모델을 생성하거나 m, 을 클릭한 다음 해당 모델을 둘러싸는 뷰를 만듭니다.

var v = new View({ model: m })

그런 다음 뷰는 기본 데이터 변경에 따라 디스플레이를 업데이트할 수 있도록 컬렉션이나 모델의 이벤트에 바인딩됩니다.뷰는 또한 Backbone에서 컨트롤러 역할을 하며 사용자 작업을 모델이나 컬렉션에 전달합니다.

초기화는 다음과 비슷해야 합니다.

$.getJSON('girls.json', function(data) {
    $.each(data, function(key, val) {
        list.push(new Girl(val));
    });

    var myGirls = new Girls(list);
    var v       = new GirlsView({ collection: myGirls });
});

그런 다음 GirlsView 컬렉션을 살펴보고 별도의 컬렉션을 만들 것입니다. GirlView각 모델의 경우:

var _this = this;
this.collection.each(function(girl) {
    var v = new GirlView({ model: girl });
    _this.$el.append(v.render().el);
});

그 다음에, GirlView 다음과 같이 렌더링됩니다.

// This could go in initialize() if you're not certain that the
// DOM will be ready when the view is created.
template: _.template($('#girl_template').html()),
render: function() {
    this.$el.html(this.template(this.model.toJSON());
    return this;
}

결과적으로 각 모델별 뷰는 고유한 고유한 뷰를 갖게 됩니다. el 이벤트를 현지화합니다.또한 모든 것이 자체적으로 잘 정리되어 있으므로 GirlView를 추가하고 제거하는 것이 매우 쉽습니다. el.

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