简体   繁体   English

骨干,触发视图事件

[英]Backbone, trigger view event

Hi I'm trying to trigger a view event after some dom modification inside the view initialize function 嗨,我尝试在视图初始化函数内部进行一些dom修改后触发视图事件

Edit: sorry for my question, it was not clear. 编辑:对不起我的问题,目前尚不清楚。 Here a full code sample. 这里是完整的代码示例。 At the end i figured out that i was triggering the change event before adding the class..feeling so stupid but i struggled for hours! 最后,我发现我是在添加类之前触发了change事件。感觉很愚蠢,但我奋斗了几个小时! Thank you for your support! 谢谢您的支持!

    <script src="https://code.jquery.com/jquery-1.12.0.js"></script>
    <script src="http://underscorejs.org/underscore.js"></script>
    <script src="http://backbonejs.org/backbone.js"></script>
    <script type="text/javascript">
    var App = {};

    (function($) {

        App.FormView = Backbone.View.extend({
                events: {
                    "change .autofill" : "autofill"
                },

                initialize : function() {
                    _.bindAll(this, "autofill");

                    this.formelements = {"input" : {"autofill" : true}};

                    for(var elementId in this.formelements){
                        if(this.formelements[elementId].autofill){
                            var $el = $("#"+elementId);
                            //$el.trigger("change").addClass("autofill")//does not work trigger before class added :-(
                            $el.addClass("autofill").trigger("change");
                        }
                    }
                },

                autofill : function(e){
                    console.log("ok");
                }
        });     

        App.init = function(containerId){
            new App.FormView({el : "#"+containerId});
        }
    })(jQuery);
    </script>


    <div id="container">
        <input type="checkbox" id="input" />
    </div>
    <script type="text/javascript">
        App.init("container");
    </script>

You're trying to trigger an event on an element that is not yet in the DOM. 您正在尝试在DOM中尚未存在的元素上触发事件。 That's not going to work, you will have to trigger your event after the view has rendered. 那是行不通的,您必须在渲染视图后触发事件。

I don't know exactly how you're rendering but consider this 我不知道你怎么渲染,但考虑一下

var View = Backbone.View.extend({

  events: {
    'change input': 'autofill'
  },

  render: function() {
    this.$el.html('<input>');
    this.$('input').trigger('change');
  },

  autofill: function(e) {
    console.log('ohai thar');
  }

});

var view = new View({
  el: $('#root')
});
view.render();

When the event is triggered on an element that is added to the document it gets picked up. 在添加到文档的元素上触发事件时,它将被拾取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM