gpt4 book ai didi

javascript - 主干网,触发 View 事件

转载 作者:行者123 更新时间:2023-12-03 07:45:49 27 4
gpt4 key购买 nike

嗨,我正在尝试在 View 初始化函数中进行一些 dom 修改后触发 View 事件

编辑:抱歉我的问题,不清楚。这是完整的代码示例。最后我发现我在添加类(class)之前触发了更改事件..感觉很愚蠢,但我挣扎了几个小时!感谢您的支持!

    <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>

最佳答案

您正尝试在尚未位于 DOM 中的元素上触发事件。这是行不通的,您必须在 View 渲染后触发事件。

我不知道你到底是如何渲染的,但请考虑 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();

当添加到文档的元素上触发该事件时,该事件就会被拾取。

关于javascript - 主干网,触发 View 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35211115/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com