Hyp*_*per 5 jquery javascript-events backbone.js
我有一个创建和填充选择列表的视图.我想在Change事件上绑定一个事件(当用户选择一个不同的Option时.
它只是输出接近这个的东西:
<select>
<option value="id">ID Name</option
</select>
Run Code Online (Sandbox Code Playgroud)
风景:
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();
}
});
Run Code Online (Sandbox Code Playgroud)
会话模板很简单:
<option value="{{Id}}">{{Name}}</option>
Run Code Online (Sandbox Code Playgroud)
事件永远不会被触发,似乎它没有正确绑定.我想在更改选择列表时触发它.
我原本以为我可能遇到类似于: backbone.js事件和el的问题,但是在这种情况下它不起作用.
很难直接调试你的问题,因为我们没有所有的信息(SessionList看起来像什么......模板等).
但是,我已将您的示例与事件所在的某些代码配对,确实有效.希望你可以从那里建立它?如果你想到达一个失败的地方,你可以分叉jsFiddle,我们可以尝试进一步提供帮助.
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);
Run Code Online (Sandbox Code Playgroud)
给定该代码,每次选择项目时,您将获得一个带有值的控制台日志.
既然你没有得到那个,我猜你是在看到一个异常或类似的东西?你的调试器给你提供了什么提示吗?
祝好运!
| 归档时间: |
|
| 查看次数: |
8598 次 |
| 最近记录: |