【问题标题】:backbone jquery-ui dialog buttons external function主干 jquery-ui 对话框按钮外部函数
【发布时间】:2013-07-09 06:50:23
【问题描述】:

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

【问题讨论】:

  • 关于这个问题的一点背景:我按原样运行了上面的代码,似乎引擎找不到提交:未捕获的类型错误:无法调用未定义 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

标签: jquery-ui backbone.js dialog


【解决方案1】:

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/ 一起玩

【讨论】:

  • 酷,谢谢!像这样,我什至可以将地图调用移到渲染函数之外!
猜你喜欢
  • 1970-01-01
  • 2016-01-31
  • 1970-01-01
  • 1970-01-01
  • 2010-12-20
  • 2010-10-31
  • 2011-02-01
  • 2011-01-28
  • 1970-01-01
相关资源
最近更新 更多