Search code examples
jquerybackbone.js

Multiple jQuery objects in Backbone view


I am using JQuery and Backbone to build a website, and it seems like a recent update in Chrome has caused some weird behaviour. Here is my Backbone.js view class:

var WebView = Backbone.View.extend({

    el: '#WebView',

    initialize: function() {
        ... // Do initialize actions

        // Arm the featured works link.
        this.$featuredWorks = $('a[href^="#"]').on('click',this.scrollTo);
    },

    scrollTo: function(e) {
        e.preventDefault();
        $(e.currentTarget.getAttribute('href')).ScrollTo();
    },
});

The thing is, the jQuery object works differently inside the View object as opposed to outside of it. I have imported a jQuery extension that adds $.fn.ScrollTo to jQuery, but it is only acccessible from outside the View, like so:

console.log($.fn.ScrollTo); // Returns the function.
var WebView = Backbone.View.extend({
    initialize: function() {
        console.log($.fn.ScrollTo); // Returns null.
    },
});

Thus, to get ScrollTo working inside the View, I have to do the following:

var jq = jQuery;
var WebView = Backbone.View.extend({
    initialize: function() {
        console.log(jq.fn.ScrollTo); // This works. 
    },
});

Does anyone know why this is the case? Why does there seem to be 2 separate jQuery objects? This script is loaded via AJAX and run using $.parseHTML. Does this have anything to do with why this is happening?


Solution

  • This has been fixed. Turns out, I included jQuery twice in my HTML template document. The second one is deferred, so it loaded when all my other scripts were loaded. So the jQuery object on frame 1 is different from the jQuery objects after that.