Reputation: 19
Hi I'm trying to trigger a view event after some dom modification inside the view initialize function
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! 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>
Upvotes: 0
Views: 787
Reputation: 17878
You're trying to trigger an event on an element that is not yet in the 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.
Upvotes: 1