2

对于渲染函数内的 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
4

1 回答 1

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;
    }
});

请参阅http://jsfiddle.net/nikoshr/AmRkp/3/

于 2013-07-09T08:37:25.923 回答