2

我已经让我的下拉列表中填充了课程,但后来我被困在试图弄清楚如何让我的下拉列表下方的文本根据用户使用 Backbone.js 选择的内容进行更改

我通过添加包含我的课程并显示标题的选项来填充选择。现在我只是停留在我应该在哪里插入文本,以便它会根据选择而改变。

这是我的 HTML:

<script type="text/template" id="lesson-template">
<span class="lesson-title"><%= title %></span>
//How should I insert the text?
</script>

<script type="text/template" id="library-template">
<h1> Lesson Library </h1>
<select class="lessons"></select>
</script>

这是我提取信息的 JSON 文件,我现在想显示标题: [{ "title": "Intro", "text":"Do this now" }, { "title": "Second", " text":"然后是这个" }]

这是我的 javascript 文件中包含的内容:

window.Lesson = Backbone.Model.extend({});

window.Lessons = Backbone.Collection.extend({
    model: Lesson,
    url: './lessons.json'
});

window.library = new Lessons();

window.LessonView = Backbone.View.extend({
    tagName: 'option',
    className: 'lesson',
    initialize: function() {
        _.bindAll(this,'render');
        this.model.bind('change',this.render);
        this.template = _.template($('#lesson-template').html());
    },

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


window.LibraryLessonView = LessonView.extend({
});

window.LibraryView = Backbone.View.extend({

    tagName: 'section',
    className: 'library',

    initialize: function() {
        _.bindAll(this, 'render');
        this.template = _.template($('#library-template').html());
        this.collection.bind('reset', this.render);
    },

    render: function() {

        var $lessons,
        collection = this.collection;

        $(this.el).html(this.template({}));
        $lessons = this.$('.lessons');
        this.collection.each(function(lesson) {
            var view = new LibraryLessonView({
                model: lesson,
                collection: collection
            });
            $lessons.append(view.render().el);
        });
        return this;
    }
});
4

1 回答 1

3

首先给id每节课一个。

window.LessonView = Backbone.View.extend({
    ...
    render: function() {
        var renderedContent = this.template(this.model.toJSON());
        $(this.el).html(renderedContent);

        // Then put the id as the option's value
        $(this.el).val(this.model.get('id'));

        return this;
    }
    ...
});

window.LibraryView = Backbone.View.extend({
    ...
    // bind the select's onchange event to this.onSelect
    events: {
        'change select': 'onSelect'
    },
    ...

    ...
    onSelect: function(e) {
        // Grab the id of the select lesson
        var lessonId = $(e.target).val();

        // And get the lesson data back
        var lesson = _.indexBy(this.collection.toJSON(), 'id')[lessonId];

        // Then you could render you lesson view with something like this :
        $('#target-container').html(
            _.template($('#lesson-template').html(), lesson)
        );

    },
    ...

});

您也可以使用更精细的视图/集合构造,但我建议您先进行此操作。

于 2013-10-10T16:19:01.763 回答