gpt4 book ai didi

javascript - 如何使用 backbone.js 路由触发 JavaScript 函数

转载 作者:行者123 更新时间:2023-11-30 12:38:32 27 4
gpt4 key购买 nike

首先,这是我试图用来声明路由的一小段代码 -

<script>
var Workspace = Backbone.Router.extend({

routes: {
"test": "test", // #test
},

test: hideone() {
...
},

});
</script>

我正在努力做到这一点,以便当有人到达“www.website.com/index.html#test”时,它会触发 JavaScript 函数“hideone”,我已经在文档的前面部分写了出来。

如果有帮助,这里是“hideone”-

<script>

function hideone() {
var elem = document.getElementById("one");
elem.className = "hide";
}
</script>

我以前从未使用过 backbone.js,我在这里找不到针对我的特定问题的文档。

最佳答案

您需要创建一个路由器实例,您还需要调用 Backbone.history.start .来自 Backbone documentation :

When all of your Routers have been created, and all of the routes are set up properly, call Backbone.history.start() to begin monitoring hashchange events, and dispatching routes.

因此您需要在脚本末尾添加这两行:

var router = new Workspace();
Backbone.history.start();

您还需要考虑@w1zeman1p 所说的关于定义测试函数的内容。调用Backbone.Router.extend接收一个对象,其中一个属性名为 test并且其值必须是一个函数。您可以内联定义它或为其分配 hideOne 函数:

//opt1 - assign an existing function
test: hideOne

//opt2 - inline
test: function(){
//function code
}

我创建了 this fiddle用第一种方法。

编辑

确保在头部或关闭主体之前按以下顺序包含脚本(作为引用,您可以通过右键单击“结果” Pane 并选择检查来在 fiddle 上检查它):

<head>

<!-- Include JS libraries before closing the head. You could also move them inside the body, right before the closing </body> -->
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.0.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js"></script>
<!-- Your code here in another <script> tag -->
</head>

然后您可以将您的 JS 包含在另一个 <script> 中在结束前标记 </head>或收盘前</body> . (请注意,您不需要从上面的 url 加载库,我只是想澄清库的顺序)

关于javascript - 如何使用 backbone.js 路由触发 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25293991/

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