I'm learning Backbone and had some issues with the on()-function. But actually it's a very basic JavaScript question.
Why is it that the first line of code below works, and the second doesn't? Using the second line, the render-function is never triggered. Mind the brackets.
Works
this.collection.on( 'reset', this.render, this );
Fails
this.collection.on( 'reset', this.render(), this );
The on() is an inbuilt method in jQuery which is used to attach one or more event handlers for the selected elements and child elements in the DOM tree. The DOM (Document Object Model) is a World Wide Web Consortium standard.
jQuery (a library built on Javascript) has built in functions that generally required the DOM to be fully rendered before being called. The syntax for when this is completed is: $(document). ready(function() { });
Answer: Use the syntax $. fn. myFunction=function(){} The syntax for defining a function in jQuery is little bit different from the JavaScript.
$( document ). ready() A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ). ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
this.render()
executes function (so in your case you are passing data returned from this function), whereas this.render
is handler to function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With