在主干视图上触发事件

Triggering an event on el in Backbone View

本文关键字:事件 视图      更新时间:2023-09-26

我有一个创建并填充Selectlist的视图。我想在Change事件上绑定一个事件(当用户选择不同的选项时)。

它简单地输出类似于这样的内容:

<select>
   <option value="id">ID Name</option
</select>

视图:

App.Views.SessionList = Backbone.View.extend({
   tagName: 'select',
   id: 'sessionList',
   events: {
       'change': 'selectionChanged'
   },
   initialize: function () {
       // Load Collection
       _.bindAll(this, 'selectionChanged');
       this.template = _.template($('#optionsTemplate').html());
       this.Sessiontemplate = _.template($('#session_template').html());
       this.SelectedSessiontemplate = _.template($('#selected_session_template').html());
       // Create Collection
       this.SessionList = new App.Collections.SessionList();
       // Set Bindings
       this.SessionList.bind('add', this.addSession, this);
       this.SessionList.bind('reset', this.addSessions, this);

       this.render();
       this.SessionList.fetch();
   },
   render: function () {
       return this;
   },
   addSession: function (item, num) {
       if (num === 0) {
           $(this.el).append(this.SelectedSessiontemplate(item.toJSON()));
           console.log("Selected");
       }
       else {
           $(this.el).append(this.Sessiontemplate(item.toJSON()));
       }
   },
   addSessions: function () {
       var self = this;
       // Add all Rows
       for (var i = 0; i < self.SessionList.models.length; i++) {
           this.addSession(self.SessionList.models[i], i);
       }
   },
   selectionChanged: function (e) {
       var field = $(e.currentTarget);
       var value = $("option:selected", field).val();
   }
});

会话模板只是简单的:

<option value="{{Id}}">{{Name}}</option>

事件从未被触发,并且它似乎没有被正确绑定。我想在改变选择列表时触发它

我原本以为我可能有一个类似的问题:

很难直接调试您的问题,因为我们没有所有的信息(SessionList看起来像什么……模板等)。

但是,我已经将您的示例配对到事件确实工作的一些代码。希望你能从这里开始?如果你想让jsFiddle失败,你可以fork它,我们可以试着进一步帮助你。

window.App = { Views: {} };
App.Views.SessionList = Backbone.View.extend({
    tagName: 'select',
    events: {
        'change': 'selectionChanged'
    },
    initialize: function () {
        _.bindAll(this, 'selectionChanged');
        this.render();
    },
    render: function () {
        $(this.el).append('<option value="foo">Option 1</option>');
        $(this.el).append('<option value="bar">Option 2</option>');                
        return this;
    },
    selectionChanged: function (e) {
        var value = $(e.currentTarget).val();
        console.log("SELECTED", value);
    }
});
var view = new App.Views.SessionList();
$("body").append(view.el);

给定该代码,您将在每次选择项目时获得一个带有值的控制台日志。

既然你没有得到,我猜你看到了一个异常或类似的东西?你的调试器给你任何提示吗?

祝你好运!