骨干视图中的多个jQuery对象 [英] Multiple jQuery objects in Backbone view

查看:66
本文介绍了骨干视图中的多个jQuery对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JQuery和Backbone构建网站,似乎Chrome的最新更新引起了一些怪异的行为.这是我的Backbone.js视图类:

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();
    },
});

问题是,jQuery对象在View对象内部的工作方式与外部不同.我已经导入了一个jQuery扩展,该扩展将$.fn.ScrollTo添加到jQuery,但是只能从视图外部访问,就像这样:

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.
    },
});

因此,要使ScrollTo在View中工作,我必须执行以下操作:

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. 
    },
});

有人知道为什么会这样吗?为什么似乎有2个单独的jQuery对象?该脚本通过AJAX加载并使用$.parseHTML运行.这与发生这种情况有什么关系吗?

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?

推荐答案

此问题已修复.事实证明,我在HTML模板文档中两次包含了jQuery.第二个脚本被推迟,因此在加载所有其他脚本时将其加载.因此,第1帧上的jQuery对象与之后的jQuery对象不同.

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.

这篇关于骨干视图中的多个jQuery对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆