对于渲染函数中的jquery-ui对话框,我是否可以使用指向另一个函数的按钮而不是内联它?
var MyView = Backbone.View.extend({
submit: function(event) { /* foo */ },
buttons: [{
'text' : 'SUBMIT',
'click' : this.submit // <== like this
}],
render: function() {
this.$el.append("I'm a dialog with a button").dialog({ buttons: this.buttons });
return this;
}
});
我按原样运行上面的代码,似乎引擎无法找到submit
:
Uncaught TypeError: Cannot call method 'apply' of undefined jquery-ui.js:10018
$.widget._createButtons.$.each.props.click jquery-ui.js:10018
jQuery.event.dispatch jquery-1.9.1.js:3074
jQuery.event.add.elemData.handle jquery-1.9.1.js:2750
答案 0 :(得分:2)
当您声明视图时会解释buttons
数组,并且此时this
设置为根对象(可能是window
)。您可以通过为window.submit
分配内容来演示此行为。例如,
window.submit = function() {
console.log('window submit');
}
单击按钮时会触发。有关演示,请参阅http://jsfiddle.net/nikoshr/AmRkp/。
您的问题的解决方案是使用您的定义作为模板为每个实例构建自定义按钮数组。像这样:
var MyView = Backbone.View.extend({
submit: function(event) {
console.log(this, 'submit');
},
buttons: [{
'text' : 'SUBMIT',
'click' : 'submit'
}],
render: function() {
var mybuttons;
//extract the buttons from an array or function,
mybuttons = _.result(this, 'buttons');
//build the array
mybuttons = _.map(mybuttons, function(obj) {
// for each object describing a button
//create a clone to avoid problems
obj = _.clone(obj);
//set the callback, bound to the view
obj.click = _.bind(this[obj.click], this);
return obj;
}, this);
this.$el.append("I'm a dialog with a button").dialog({
buttons: mybuttons
});
return this;
}
});