【问题标题】:Unable to bind click event in Backbone无法在 Backbone 中绑定点击事件
【发布时间】:2013-06-24 22:44:34
【问题描述】:

我似乎无法将点击事件绑定到下面 sn-p 中的操作。有什么想法吗?

var SelectView = Backbone.View.extend({
  template: "#select-template",
  initialize: function() {
    this.render();
  },
  events: {
    "click .placeholder": "optionsDropdown",
  },
  render: function() {
    context = {className: this.className, options: this.model.get("options"), placeholder: this.model.get("placeholder")};
    $(this.el).html(getHTML(this.template, context));
  },
  optionsDropdown: function() { 
    alert("Hello");
  },
});

【问题讨论】:

  • 如果在您的initialize 方法中您使用this.$el.on("click", this.optionsDropdown);,它是否有效?
  • @Mash:不,我刚试过。由于某种原因,我无法参与其中。
  • 你缺少一个目标元素 (el) 我对我的答案进行了更改并添加了一个工作小提琴
  • 模型中的数据是什么样的?我怀疑这条线 className: this.className 。我在视图定义中的任何地方都看不到 className 变量

标签: javascript jquery events backbone.js underscore.js


【解决方案1】:

我认为问题出在这一行

className: this.className

我在视图定义中的任何地方都没有看到 className 变量

  var SelectView = Backbone.View.extend({
    initialize: function () {
        this.className = 'placeholder';
    },
    events: {
        "click .placeholder": "optionsDropdown",
    },
    render: function () {
        context = {
            className: this.className,
            options: this.model.get("options"),
            placeholder: this.model.get("placeholder")
        };
        var template = _.template( $("#select-template").html(), context );

        this.$el.html(template);
    },
    optionsDropdown: function () {
        alert("Hello");
    },
});

var Model = Backbone.Model.extend({});

var newModel = new Model({
    'options' : 'Hello',
    'placeholder' : 'Type your name'
});

var newView = new SelectView({model : newModel});
newView.render();
$('.container').append(newView.el);

Check Fiddle

您正在为应该在模板中的class="placeholder" 绑定click 事件。一旦你定义它应该工作,只要你的模板中有那个类的元素。

Calling render from initialize

【讨论】:

    【解决方案2】:

    您在事件定义中缺少选择器。应该是这样的(假设输入 id 是 optionsId):

    events : {
        "click #optionsId": "optionsDropDown"
    }
    

    【讨论】:

    • 我们在里面有选择器——我在尝试它而不只是为了好玩。无论哪种方式都不起作用。
    • 尝试从视图本身之外调用render(),即从路由器。此外,render() 应该返回 this
    • 在路由器中你应该有这样的东西:this.elms['page-content'].html(view.render().el);
    【解决方案3】:

    您可以将 DOM 元素绑定到处理程序,例如 "click li":"optionsDropDown"

    编辑:您缺少目标元素..这是一个有效的小提琴 http://jsfiddle.net/FGeJd/

    【讨论】:

    • 这是不正确的。 “省略选择器会导致事件绑定到视图的根元素 (this.el)” - Backbone Documentation
    • 默认情况下el 将是一个 div,所以这应该不是问题
    • 是的,但在您将其插入 DOM 之前它将是一个孤儿,并且您需要执行类似 $('#selection-parent').html(new SelectView().render().el);.. 之类的操作。像 new SelectView({el: '#selection'}) 这样传入 el 会是更好的方法比拥有一个孤立的 div
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    相关资源
    最近更新 更多