在主干视图中访问el外部的点击事件

2024-03-29

我如何访问外部的点击事件el scope.

我拥有的 : HTML:

<div class="right_btn"></div>
<div id="template_loader">
    <!-- HTML template goes here which contain form inputs-->
    <input type="text" class="forgot_password_email" name="forgot_password_email"/>
</div>

View :

var ForgotPasswordView = Backbone.View.extend({
    el: "#template_loader",
    initialize: function () {
        console.log('Forgot Password View Initialized');
    },
    render: function () {
        blockPage();
        var that = this;  

        $.get(App.baseUrl + 'templates/forgot-password-view.html', function (data) {
            template = _.template(data, { });
            that.$el.html(template);
            unblockPage();
        }, 'html'); 
    },
    events:{
        'click .right_btn':'forgotPasswordSubmit', //Doesn't fire as its outside of el
    }, 
    forgotPasswordSubmit: function(e){
        alert($(".forgot_password_email").val());
        e.preventDefault();
    }
});

我经历过以下事情:

Backbone.js 视图 - 将事件绑定到“el”之外的元素 https://stackoverflow.com/questions/8274257/backbone-js-views-binding-event-to-element-outside-of-el

如何在 Backbone 子视图中绑定点击事件 https://stackoverflow.com/questions/13269071/howto-bind-a-click-event-in-a-backbone-subview

但并不能真正帮助我让它发挥作用。

我怎样才能获得点击事件.right_btn视图内。我无法更改模板结构以包含right_btn在 - 的里面el。无论如何,这里都是为了绑定外部元素或识别主干视图本身内的单击事件。


不幸的是,仅使用骨干库无法做到这一点。 Backbone 期望视图仅处理其特定 DOM 元素内的事件。

如果可能的话,最好重构您的代码,这样您就不必违反这些约定。如果您需要重新定位视图并且它依赖于其父环境,那么模糊视图的边界可能会给您带来困难。

如果可能,创建一个包含上面列出的 HTML 的父视图,并使用该视图绑定到事件并提交其子视图的表单。

如果您别无选择,只能这样做,那么我建议使用 jQuery 'on' 来绑定到事件。

// Put this in your view to ensure that it is only bound when the form is
// added to the page. You could substitute 'on' for 'one' if you don't want
// the binding to maintain after the first submission.
var submitForm = function(){
  $('#template_loader form').submit();
};
$('.right_button').on('click', submitForm);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在主干视图中访问el外部的点击事件 的相关文章

随机推荐